gpt4 book ai didi

javascript - 在成功函数之外使用通过 AJAX 检索的 JSON 数据

转载 作者:数据小太阳 更新时间:2023-10-29 04:08:50 27 4
gpt4 key购买 nike

我在将使用 AJAX 获得的 JSON 存储到外部变量以供进一步使用时遇到问题。我检查了这个答案 ( load json into variable ),这是非常基本的,但我做错了其他事情。我的代码如下。

function showZone() {
var data=null;
$.ajax({
url: 'http://localhost/gui/templates/tracking/show_zones.php',
//data: 'userid='+ uid ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
type: "POST",
success: function(json) {
data=json;
$( '#res1' ).html( data[0].swlat );

}
});
return data;

}

function showZones() {
var data=showZone();
$( '#res2' ).html( data[0].swlat );
}

为了更清楚地了解我的问题,我有两个 div(#res1 和 #res2),我在其中打印数据。在 #res1 中,我得到了想要的结果,但是 #res2 没有打印任何东西,我得到了一个错误“Uncaught TypeError: Cannot read property '0' of null”。因此数据在 ajax 将其存储在变量中之前返回。这是问题所在,还是我应该以不同的方式将 json 存储到变量中?任何帮助表示赞赏:)

最佳答案

您可以使用 callback() .考虑以下代码段:

function showZone() {
var data = null;
$.ajax({
url: 'http://localhost/gui/templates/tracking/show_zones.php',
//data: 'userid='+ uid ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
type: "POST",
success: function(json) {
data = json;
showZones(data);//callback

}
});
//return data; No need to return data when we have async ajax

}
showZone(); // call when you want to make ajax call
function showZones(data) { // This function will call after ajax response
$('#res2').html(data[0].swlat);
}

关于javascript - 在成功函数之外使用通过 AJAX 检索的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132466/

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