jQuery AJAX。 返回值未定义?
我有那个代码:
var s, d, p = ''; $.ajax( { type: "POST", url: ajaxurl, data: {action: "get_info"}, success: function(r) { // r contain that json data // {"s":"long-string","d":"string","p":"string"} // That served from the server with that header // // header('Cache-Control: no-cache, must-revalidate'); // header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // header('Content-type: application/json'); d = rd; s = rs; p = rp; } } ); // And here console return s as undefined console.log(s);
有什么问题吗?
$.ajax()
调用只是启动ajax操作。 然后代码落到你的console.log
语句中,但是ajax调用还没有返回。 因此, s
的价值尚未确定。
稍后,ajax调用会返回您的结果,此时您的回调将被触发。 因此,如果要引用返回的值,则应引用回调内的变量s
。
更好的方法通常是这样的:
$.ajax( { type: "POST", url: ajaxurl, data: {action: "get_info"}, success: function(r) { s = rs; // Do something with s here... } } );
如果你真的需要,你可以在回调之外引用s
,但如果你这样做,你需要设置一些机制来确保s
已经被初始化(即你的ajax调用已经返回)。 这引入了其他复杂性,例如同步和error handling,并且可能使您的程序流程相当不可靠。
原因是当你调用$.ajax(...);
它会立即返回。 success
属性指定在AJAX请求完成时调用的回调,并且仅在那里填充s
; 在此之前它是未定义的。
因此,在success
回调启动之前,基本上不要对s
做任何事情。
问题是您认为代码以您的布局方式执行。 它实际上在系统上与: –
var s, d, p = ''; // And here console return s as undefined console.log(s); $.ajax( { type: "POST", url: ajaxurl, data: {action: "get_info"}, success: function(r) { // r contain that json data // {"s":"long-string","d":"string","p":"string"} // That served from the server with that header // // header('Cache-Control: no-cache, must-revalidate'); // header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // header('Content-type: application/json'); d = rd; s = rs; p = rp; } } );
你可能想要的是: –
var s, d, p = ''; $.ajax( { type: "POST", url: ajaxurl, data: {action: "get_info"}, success: function(r) { // r contain that json data // {"s":"long-string","d":"string","p":"string"} // That served from the server with that header // // header('Cache-Control: no-cache, must-revalidate'); // header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // header('Content-type: application/json'); d = rd; s = rs; p = rp; // And here console return s as undefined console.log(s); } } );
尝试指定数据类型类似type: "POST", url: ajaxurl, dataType: 'json', data: {action: "get_info"},
…