2017-02-17 67 views
0

我试图找出为什么第一代码工作,而第二个则没有。我对jQuery和Javascript整体上都很满意,但是在这个“$('#location')。html(...)”部分用'location'id填充了元素。如果我创建了一个变量的方式来该请求的结果被指定,它会做同样的工作,如果我有“$(‘#位置’)。HTML(可变)”。是什么赋予了?为什么我的修改当前位置请求代码(JS/jQuery的)工作?

这里有两个代码:

第一个代码(这工作)

<!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> 
+0

谢谢你的链接。 –

+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); 

承诺有一些严重的优势,像可组合:多个处理程序可以安装。

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

我明白了。谢谢你的解释。 –

相关问题