为什么我修改的当前位置请求代码(JS / jQuery)不起作用?

时间:2017-02-17 17:48:38

标签: javascript jquery json

我试图弄清楚为什么第一个代码有效,而第二个却没有。我对jQuery和Javascript整体上有点绿色,但是这个“$('#position')。html(...)”部分的印象是用'location'id填充元素。这样,如果我创建了一个分配了请求结果的变量,那么如果我有“$('#location')。html(variable)”,它就会做同样的工作。是什么给了什么?

以下是两个代码:

第一个代码(可行)

<!DOCTYPE html> 
<html> 
  <head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Current Position</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  </head> 
  <body > 
    <div>Location: <span id="location"></span></div>
    <script>
      $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?') 
         .done (function(location) {
            $('#location').html(location.city + ", " + location.state + " (" + location.country_name + ")");               
         });
    </script>
  </body> 
</html> 

第二个代码(这个没有)

<!DOCTYPE html> 
<html> 
  <head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Current Position</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  </head> 
  <body > 
    <div>Location: <span id="location"></span></div>
    <script>
      var currentLocation = $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?') 
         .done (function(location) {
            location.city + ", " + location.state + " (" + location.country_name + ")";              
         });

      $('#location').html(currentLocation);   
    </script>
  </body> 
</html>

1 个答案:

答案 0 :(得分:2)

$.getJson会返回一种promise,而不是请求本身的值。因此,将结果分配给变量不会给您想要的结果。这是大多数异步工作的方式。您将永远无法以这种方式分配异步调用的结果,因为代码尚未成功运行。

第一个代码是正确的方法。以这种方式思考:

// Do some *asynchrounous* request
const promise = $.getJson(...arguments...)

// Create a handler funcion or "callback"
const handler = function(value) { console.log(value) }

// Tell the promise to call this function when it get's resolved
promise.done(handler);

Promise有一些严重的优点,比如可组合性:可以附加多个处理程序。

$.getJson(...)
  .done(doStuffA)
  .done(doStuffB)
  .catch(handleError)