jQuery的阿贾克斯获得结果结果、jQuery、阿贾克斯

2023-09-10 21:18:32 作者:Guard╯寂寞

下面是初始code:

var res = null;
$.post('test.php', 'q=testdata', function(response) {
   res = response;
});

我需要,或Ajax调用后,就在我的code使用 RES 在一些点。我想这样的:

I need to use res at some point in my code, or right after the ajax call. I tried this:

var res = null;
$.post('test.php', 'q=testdata', function(response) {
   res = response;
   alert('Note 1: '+res); /* Returned exactly what I wanted */
});
alert('Note 2: '+res); /* Returned null. I need to use res here. How? */

这怎么可能使用 RES 的AJAX调用后按住所需的价值呢?

How is it possible to use res to hold the desired value after the ajax call?

推荐答案

您code,使异步Ajax请求,而第二个警报同步执行。这意味着,(按顺序)第二警报执行时的响应可能不可用。

Your code makes an asynchronous ajax request while the second alert executes synchronously. This means that a response may not be available when the (sequentially) second alert executes.

尝试把这个你的 $交背后电话: $ ajaxSetup({异步:假})

Try putting this behind your $.post call: $.ajaxSetup({async:false}).

这将迫使警告射击,因为它们出现在你的code的顺序。如果一个异步调用是你想要做什么,那么我建议你遵循的Sudhir的意见。

It will force the alerts to fire in the order that they appear in your code. If an async call is what you want to make, then I suggest you follow Sudhir’s advice.