HTML5地理定位 - 将数据替换/添加到Ajax URL字符串

时间:2015-05-26 17:18:38

标签: jquery html ajax json geolocation

所以我试图获取用户位置,然后使用jQuery将位置坐标替换为纬度和经度的json URL请求,然后将其输出到页面上的ElementByID。

以下是我提出的建议,但它似乎并没有起作用。而不是替换字符串,它输出为http://api.wunderground.com/api/My-API-key/geolookup/conditions/q/+position.coords.latitude+,+position.coords.longitude+.json

以下是代码,

<a id="demo"></a>

<script>
    var x = document.getElementById("demo");


    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }


jQuery(document).ready(function showPosition(position) {
  $.ajax({
  url : "http://api.wunderground.com/api/MY-API-KEY/geolookup/conditions/q/" + position.coords.latitude + "/" + position.coords.longitude + ".json",
  dataType : "jsonp",
  success : function(parsed_json) {
  var location = parsed_json['location']['city'];
  var temp_f = parsed_json['current_observation']['temp_f'];
    x.innerHTML = location + temp_f
  }
  });
});


</script>

我使用HTML5地理定位功能来获取位置,然后我尝试替换ajax URL,在末尾添加位置数据以输出正确的温度,但由于某种原因,它似乎没有工作。

任何想法和提示都会很棒!

2 个答案:

答案 0 :(得分:1)

好的,我明白了。以下是答案。问题是我试图用另一个函数中的变量替换结束URL。我只需要在正确的函数中包含json请求,以便读取/访问变量。

我感到愚蠢,以前我没有看到它。哈哈

<a id="demo"></a>

<script>
    var x = document.getElementById("demo");


    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }

function showPosition(position) {

    var location = position.coords.latitude + 
    "," + position.coords.longitude;    


jQuery(document).ready(function($) {

  $.ajax({
  url : "https://api.wunderground.com/api/MY-API-KEY/geolookup/conditions/q/"+location+".json",
  dataType : "jsonp",

  success : function(parsed_json) {
  var location = parsed_json['location']['city'];
  var temp_f = parsed_json['current_observation']['temp_f'];
  x.innerHTML = "Current temperature in " + location + " is: " + temp_f;
  }
  });
});
   }   

</script>

答案 1 :(得分:0)

试试这个: - )

  function showPosition(position) {
      $.ajax({
      url : "http://api.wunderground.com/api/My-API-key/geolookup/conditions/q/" +position.coords.latitude+ "," +position.coords.longitude+ ".json",
      dataType : "json",
      type : 'post',
      data: { changeThis: position.coords.latitude,
              changeThis: position.coords.longitude
       },
      success : function(data) {
        if(data.success){
            alert("hello");

           }

      }