2017-02-17 65 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

我明白了。謝謝你的解釋。 –

相關問題