Javascript JQUERY/JSON数据未定义,然后神秘地定义

Javascript JQUERY/JSON数据未定义,然后神秘地定义,javascript,jquery,json,Javascript,Jquery,Json,我有一个脚本可以读取一些JSON数据: var tempJson; $.post("scripts/getJSON.php", function(data) { tempJson = data; }, 'json'); alert(""); //First alert alert("That: " + tempJson); //Second alert 当我包括第一个警报行时,第二个警报会按预期给我一个[Object]。当我省略第一个警报行时,我会在第二个警报中收到未定义的警报。

我有一个脚本可以读取一些JSON数据:

var tempJson;
$.post("scripts/getJSON.php", function(data) {
     tempJson = data;
}, 'json');
alert("");  //First alert
alert("That: " + tempJson);  //Second alert

当我包括第一个警报行时,第二个警报会按预期给我一个[Object]。当我省略第一个警报行时,我会在第二个警报中收到未定义的警报。为什么?

在我看来,这是一个时间问题。您正在启动一个请求,然后在post脚本之后立即检查回调中的值,而不是检查回调中的值。AJAX是异步的…aka异步JavaScript和XML

var tempJson;
$.post("scripts/getJSON.php", function(data) {
     tempJson = data;

     // Callback here, response has most definitely happened
     alert(tempJson);
}, 'json');

// Response may not have happened yet when this is executed
alert("");  //First alert
// Still might not have happened when this is executed
alert("That: " + tempJson);  //Second alert

在我看来,这是一个时间问题。您正在启动一个请求,然后在post脚本之后立即检查回调中的值,而不是检查回调中的值。AJAX是异步的…aka异步JavaScript和XML

var tempJson;
$.post("scripts/getJSON.php", function(data) {
     tempJson = data;

     // Callback here, response has most definitely happened
     alert(tempJson);
}, 'json');

// Response may not have happened yet when this is executed
alert("");  //First alert
// Still might not have happened when this is executed
alert("That: " + tempJson);  //Second alert

因为它是异步的,当您关闭警报时,ajax已经完成,数据已经返回并分配给变量

你应该

var tempJson;
$.post("scripts/getJSON.php", function(data) {
     tempJson = data;
     alert(tempJson); // or whatever you want to do with the data should go here..
}, 'json');

因为它是异步的,当您关闭警报时,ajax已经完成,数据已经返回并分配给变量

你应该

var tempJson;
$.post("scripts/getJSON.php", function(data) {
     tempJson = data;
     alert(tempJson); // or whatever you want to do with the data should go here..
}, 'json');

默认情况下,jQueryAjax是同步的。因此,如果您的请求延迟了一点,您的警报将没有请求数据。正确的方法是在回调中发出警报


目前,您可以将AJAX请求更改为synchronous,但现在jQuery不推荐使用它,它会挂断您的浏览器。因此,最好的方法是使用的success/complete/error callback/event。

jQuery AJAX在默认情况下是同步的。因此,如果您的请求延迟了一点,您的警报将没有请求数据。正确的方法是在回调中发出警报


目前,您可以将AJAX请求更改为synchronous,但现在jQuery不推荐使用它,它会挂断您的浏览器。因此,最好的方法是使用success/complete/error callback/event of.

您应该使用
console.log
,因为它不会停止脚本的执行尝试以下操作:tempJson=$.parseJSON(数据);您应该使用
console.log
,因为它不会停止脚本的执行尝试以下操作:tempJson=$.parseJSON(数据);