【问题标题】:Using JSON data retrieved with AJAX outside success function在成功函数之外使用通过 AJAX 检索到的 JSON 数据
【发布时间】:2016-09-05 01:46:24
【问题描述】:

我在将通过 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 存储到变量中? 任何帮助表示赞赏:)

【问题讨论】:

  • 使用简单的回调。
  • 加载的数据存储在成功函数中

标签: javascript jquery json ajax


【解决方案1】:

您可以使用callback()。考虑以下 sn-p:

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

【讨论】:

    【解决方案2】:

    $.ajax 立即返回return data,它在你作为成功回调传递的函数被调用之前执行。所以它返回为未定义。这意味着你不能返回 ajax 数据。

    更多示例How do I return the response from an asynchronous call?

    但你为什么不能简单地使用like

      success: function(json) {
                data=json;
                $( '#res1' ).html( data[0].swlat );  
                $( '#res2' ).html( data[0].swlat ); 
            }
    

    【讨论】:

    • 谢谢你的链接,我在想问题是这样的。我真的不需要在 div 中显示数据,这只是为了演示我的问题,我只想在 ajax 函数之外使用 JSON 数据。不过我会通过回调解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多