Переменная в SRC - PullRequest
       5

Переменная в SRC

0 голосов
/ 06 марта 2020

Я вставил в свой код HTML виджет погоды, который показывает погоду в городе пользователя. Я пытаюсь с помощью скрипта геолокации показать погоду местоположения IP, потому что виджет зафиксирован в городе, но я понятия не имею, как показать переменную в URL SR C, вот мой код, не могли бы вы помочь мне решить мою проблему, я бы очень признателен:

    <script id="imageBox" type="text/javascript" class="w3-bar-item w3-button w3-center" src=""></script>
    <script type="text/javascript">
$.ajax({
  url: "https://get.geojs.io/v1/ip/geo.js",
  jsonpCallback: "geoip",
  dataType: "jsonp",
  success: function(location) {
    $('#country').html(location.country_name);
    $('#countrycode').html(location.country_code);
    $('#state').html(location.state);
    $('#city').html(location.city);
    $('#latitude').html(location.latitude);
    $('#longitude').html(location.longitude);
    $('#ip').html(location.ip);
  var latitudevar = location.latitude;
  var longitudevar = location.longitude;
  document.getElementById('imageBox').src = 'https://darksky.net/widget/default-small/' + latituidevar + ',' + longitudevar + '/uk12/en.js?width=50%&height=70&title=Full Forecast&textColor=000000&bgColor=transparent&transparency=true&skyColor=undefined&fontFamily=Default&customFont=&units=uk';

  }

}); 
    </script>

1 Ответ

0 голосов
/ 08 марта 2020

Понятно, вы меняете sr c тега script. Это невозможно. Это работает только в медиа-тегах, таких как img или iframe. Вы должны создать новый тег сценария.

В конце кода AJAX запросов вы можете сделать это следующим образом:

// source attribute
let src = 'https://darksky.net/widget/default-small/' + latituidevar + ',' + longitudevar + '/uk12/en.js?width=50%&height=70&title=Full Forecast&textColor=000000&bgColor=transparent&transparency=true&skyColor=undefined&fontFamily=Default&customFont=&units=uk';

// create a script tag and set the source
let s = document.createElement('script');
s.src = src;

// find the head tag and append the script tag
document.getElementsByTagName('head')[0].appendChild(s);

И вы можете полностью удалить

<script id="imageBox" type="text/javascript" class="w3-bar-item w3-button w3-center" src=""></script>

Также я не могу представить, почему вы даете атрибут класса тегу script, потому что он никогда не отображается в DOM.

...