gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:59:34 26 4
gpt4 key购买 nike

我试图找出为什么第一个代码有效而第二个代码无效。总的来说,我对 jQuery 和 Javascript 有点陌生,但印象中这个“$('#location').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>

最佳答案

$.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)

关于javascript - 为什么我修改后的当前位置请求代码 (JS/jQuery) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42304371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com