1

我得到了一个 Jquery ajax 调用,它从我得到的 php 文件中获取 json 响应,json 响应很棒,我可以正确地控制台记录响应,但是我似乎无法将信息保存在 ajax 结果之外,它不会更新数组。代码看起来像这样,我在下面发布了结果。

window.array={name: 'john',color:'red'};    

 console.log(array['name']);
 console.log(array['color']);

$.ajax({
    url : 'getJsons.php',
    type : 'POST',
    data : data,
    dataType : 'json',
    success : function (data) {

      array['name'] = data['name'];
      array['color'] = data['color'];
      console.log(array['name']);
      console.log(array['color']);
     }        
});

 console.log(array['name']);
 console.log(array['color']);

这将导致以下控制台:

 john
 red

 john
 red

 marry
 blue

所以我第一次得到控制台,但它似乎在 ajax 调用之前在 ajax 调用之后加载脚本,这是为什么呢?因为这使我无法在其余代码中使用 ajax 结果,因为它是在脚本加载后获取的。有没有办法让 ajax 在其余部分之前运行?

4

4 回答 4

4

由于您无法判断来自服务器的 ajax 响应何时到达,因此默认情况下 AJAX 是异步的。这意味着$.ajax触发了get,然后javascript引擎继续执行您的其余代码(在您的示例中console.log,ajax调用之外的两个s)。在未来的某个地方,ajax 调用可能(也可能不会)从服务器获得响应(并通过更改其状态来通知这一点)。此时,javascript 引擎将处理所谓的“回调”函数 - 将在 ajax 调用完成时执行的代码。您将回调函数定义为successajax 方法的参数。

这就是为什么执行代码的正确方法是运行取决于回调函数结果的所有内容。将所有内容直接放在那里,或者声明一个单独的函数,然后您可以在成功函数中调用它:

$.ajax({
    /*...*/,
    success : function (data) {

      array['name'] = data['name'];
      array['color'] = data['color'];

      /* either put all your dependent code here */

      /* or just call a callback function: */
      callback(data);

     }        
});

/* code to be executed after the ajax call */
function callback(data){

   // work with the response here
   console.log(data);

}

前面的坏主意:

或者,您可以告诉调用是同步的(这很糟糕,因为您的浏览器在等待服务器响应时基本上被冻结)并保持您的代码不变。

$.ajax({
      /*...*/,
      async : false,     
});
// risk some waiting time (possibly the full duration of a timeout!!)
// the browser is locked during this time

// continue normally
console.log(array['name']);
console.log(array['color']);
于 2013-09-17T13:50:49.590 回答
1

发生的事情是在 ajax 调用完成之前运行查询之后的代码。您的数组已被填充,不用担心,但因为 AJAX 异步运行,它只会在 ajax 调用之后分配值。

例如,如果您在 ajax 调用后设置 10 秒超时(取决于 AJAX 调用执行的时间)然后调用数组值,您会发现它们已填充(假设 AJAX 已运行并正确通过回调函数)。

所以在你的代码中,一步一步发生了什么。

You display the values from the array which shows john red

You make the AJAX call, when this call has completed it will perform your success: function

The ajax call takes (lets say) 1 second to complete

Whilst your page is waiting for the call to complete and update the values it moves onto the next bit of code which displays the array, as the array hasn't been updated yet as success hasn't been called it still displays john red

1 seconds later the success function is called, assigns the new names to the array and prints them out.

于 2013-09-17T13:46:02.033 回答
1

ajax 调用是异步的,这意味着无论何时执行和返回 ajax,其余代码都将被执行。如果您的代码取决于结果,请将其包装在一个函数中并从 ajax 的回调(成功函数)中调用它。

于 2013-09-17T13:46:09.170 回答
0

我不知道这些东西是否是标准的东西,但它的工作:

var xmlURL = "Data/XML/"+GetURLParameter("xml");
var xmlInto = {};

$.get(xmlURL, function(xml) {
    $(xml).find("line").each(function(){
        xmlInto[line_number] = line_info;
    });             
}, 'xml');

console.log(xmlInto);
于 2013-09-17T14:01:43.983 回答