使用 Jquery 将 ajax 响应保存到数组

saving ajax response to array with Jquery

本文关键字:保存 数组 响应 ajax Jquery 使用      更新时间:2023-09-26

我接到一个 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 在其余部分之前运行?

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

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

$.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']);

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

正在发生的事情是在 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.

我不知道

这些东西是否是标准的东西,但它是工作:

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);