简体   繁体   English

使用AJAX检索外部成功函数的JSON数据

[英]Using JSON data retrieved with AJAX outside success function

I have a problem with storing JSON that I get with AJAX, to an outside variable for further usage. 我将使用AJAX存储的JSON存储到外部变量以供进一步使用时遇到问题。 Ive checked this answer ( load json into variable ) which is really basic, but I'm doing wrong something else. 我已经检查了这个答案(将json加载到变量中 ),这是非常基本的,但我做错其他的事情。 My code is below. 我的代码如下。

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

For clearer picture of my problem I have two divs (#res1 & #res2), where I print the data. 为了更清楚地了解我的问题,我有两个div(#res1&#res2),我打印数据。 In #res1 I get the result as wanted, but #res2 doesnt print anything and I get an error 'Uncaught TypeError: Cannot read property '0' of null'. 在#res1中,我得到了想要的结果,但是#res2没有打印任何东西,我得到一个错误'未捕获的TypeError:无法读取null'的属性'0'。 So the data is returned before ajax stores it in a variable. 因此,在ajax将其存储在变量中之前返回数据。 Is this the problem, or should I be storing json to a variable differently? 这是问题,还是我应该以不同的方式将json存储到变量中? Any help appreciated :) 任何帮助赞赏:)

You can use callback() . 你可以使用callback() Consider following snippet: 请考虑以下代码段:

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

$.ajax returns immediately return data which is executed before the function you passed as success callback was even called.So its return as undefined .Its means you can't return ajax data . $ .ajax立即return data ,该return data在您传递的函数之前执行,因为甚至调用了成功回调。因此返回为未定义.Its表示您无法返回ajax数据。

For more example How do I return the response from an asynchronous call? 有关更多示例如何从异步调用返回响应?

But why can't you use simply like 但为什么你不能简单地使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM