Javascript 为什么赢了';我修改过的当前位置请求代码(JS/jQuery)是否有效?

Javascript 为什么赢了';我修改过的当前位置请求代码(JS/jQuery)是否有效?,javascript,jquery,json,Javascript,Jquery,Json,我试图弄明白为什么第一个代码有效,而第二个代码无效。我对jQuery和Javascript整体上有点生疏,但我的印象是,“$('.#location').html(…)”部分用'location'id填充元素。这样,如果我创建了一个变量,请求结果将被分配到该变量,如果我有“$('.#location').html(variable)”,它也会做同样的工作。有什么好处 以下是两个代码: 第一个代码(这很有效) 当前位置 地点: $.getJSON('https://geoip-db.com/js

我试图弄明白为什么第一个代码有效,而第二个代码无效。我对jQuery和Javascript整体上有点生疏,但我的印象是,“$('.#location').html(…)”部分用'location'id填充元素。这样,如果我创建了一个变量,请求结果将被分配到该变量,如果我有“$('.#location').html(variable)”,它也会做同样的工作。有什么好处

以下是两个代码:

第一个代码(这很有效)


当前位置
地点:
$.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?') 
.完成(功能(位置){
$(“#location').html(location.city+”、“+location.state+”(“+location.country_name+”));
});
第二个代码(这一个没有)


当前位置
地点:
var currentLocation=$.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?') 
.完成(功能(位置){
location.city+,“+location.state+”(“+location.country\u name+”);
});
$('#location').html(currentLocation);

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

第一个代码这是正确的方法。这样想:

// 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)

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

第一个代码这是正确的方法。这样想:

// 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)

我懂了。谢谢你的解释,我明白了。谢谢你的解释。不客气。不客气。