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

Gre*_*par 8 javascript ajax jquery json

我将使用AJAX存储的JSON存储到外部变量以供进一步使用时遇到问题.我已经检查了这个答案(将json加载到变量中),这是非常基本的,但我做错其他的事情.我的代码如下.

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 );  
}
Run Code Online (Sandbox Code Playgroud)

为了更清楚地了解我的问题,我有两个div(#res1&#res2),我打印数据.在#res1中,我得到了想要的结果,但是#res2没有打印任何东西,我得到一个错误'未捕获的TypeError:无法读取null'的属性'0'.因此,在ajax将其存储在变量中之前返回数据.这是问题,还是我应该以不同的方式将json存储到变量中?任何帮助赞赏:)

Man*_*wal 6

你可以使用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);
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*pan 5

$ .ajax立即返回return data,在您传递的函数之前执行,因为甚至调用了成功回调.因此返回为undefined .Its表示您无法返回ajax数据.

有关更多示例如何从异步调用返回响应?

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

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