【问题标题】:Pushing to Javascript Array from Jquery JSON request从 Jquery JSON 请求推送到 Javascript 数组
【发布时间】:2010-03-09 16:58:15
【问题描述】:

为什么这段代码总是返回 0?

     var possibleMatches = new Array();
  $.getJSON('getInformation.php', function(data) {
   $.each(data, function(i){
    possibleMatches.push(data[i]);
   })
  });
  alert(possibleMatches.length);

虽然我可以移动或添加“alert(possibleMatches.length);”在 $.each 中,它将输出正确数量的元素。

我只是好奇为什么这些值没有像我预期的那样进入数组。我确定这是一个局部变量与全局变量的问题,只是不知道为什么。

基本上,它试图做的是用数据结果填充 possibleMatches 数组。

谢谢!

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:

    异步性。 alert(possibleMatches.length); 行在 $.getJSON() 的成功回调执行之前执行。

    因此,要准确地生成警报报告,只需移动它即可。

    var possibleMatches = new Array();
    $.getJSON('getInformation.php', function(data) {
      $.each(data, function(i){
        possibleMatches.push(data[i]);
      })
    
      // To here
      alert(possibleMatches.length);
    });
    // From here
    

    记住,AJAX 中的第一个 A 代表“异步”

    【讨论】:

    • @Peter Bailey-Doh!我怎么会忘记那个小(但非常重要)的部分!这很有意义!谢谢!
    【解决方案2】:

    $.getJSON 执行异步调用,其回调在使用的 xmlhttprequest 完成时执行:

    var possibleMatches = new Array(); 
    $.getJSON('getInformation.php', function(data) {  // <-- this will run later 
        $.each(data, function(i){ 
            possibleMatches.push(data[i]); 
        }) 
    }); 
    alert(possibleMatches.length);  // this will call immediately
    

    【讨论】:

      【解决方案3】:

      jetJSON 请求是异步的,它在警报运行后完成。如果您想要一个准确的警报,它应该在您的 getJSON 回调中,如下所示:

        $.getJSON('getInformation.php', function(data) {
         $.each(data, function(i){
          possibleMatches.push(data[i]);
         });
         alert(possibleMatches.length);
        });
      

      【讨论】:

        猜你喜欢
        • 2017-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-29
        • 2019-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多