为什么我对类似的ajax请求得到不同的回应?

时间:2014-07-17 13:03:23

标签: javascript php jquery ajax

issue resolved, see edit : both the php scripts are returning json_encode()'d 2D arrays, but one response(trains) is received as a multidimensional array and the other(data) as an object, why is this happening?

其次,console.log(data)行是在console.log(allData)之后执行的,不应该是反过来的吗?我需要使用数据中包含的响应填充allData。这是代码:

$(document).ready(function() {
$("form").submit(function(){    
    event.preventDefault();

    $.ajax({
      //type: "POST",
      url: "./trains_bw_stations.php",
      dataType: 'json',
      data: { source: $('input[name*="src"]').val(), destination: $('input[name*="dstn"]').val(), 
                day: $('input[name*="day"]').val(), month: $('input[name*="month"]').val(), cl: $('input[name*="cl"]').val()  }
    })
      .done(function(trains) {
        console.log(trains)
        var requests = [], allData = {};

        for (var i = 0; i < trains.length; i++) {
            console.log(trains[i][0]);
            requests.push($.ajax({
                url: './availability.php', 
                dataType: 'json',
                data: { 
                        day: $('input[name*="day"]').val(), month: $('input[name*="month"]').val(),lccp_trndtl: trains[i][0]  }
                // success: function(data) {
                //  console.log(data);
                //     allData[''+i] = data;

            }).done(function(data) {
                    console.log(data);
                    allData[i] = data})
            );
        }

        $.when.apply(requests).then(function() {

            console.log(allData)
        for (var i in allData) {
          if (allData.hasOwnProperty(i)) {
            console.log(i+ " -> " + allData[i])
              }
            }
            // all requests have completed
            // allData array now contains the data from all the requests
            // put your processing logic in here...
        });
    });

});
});

复制粘贴的控制台输出,它显示在34之前执行的第41行:

[Array[15], Array[15], Array[15]] ajaxRequests.js:19
12650NZM KCG NYYNYNYYA ajaxRequests.js:23
12724NDLSHYB NYYYYYYYA ajaxRequests.js:23
12722NZM HYB YYYYYYYYA ajaxRequests.js:23
Object {} ajaxRequests.js:41
Object {0: Array[4], 2: Array[4], 4: Array[4], 6: Array[4], 8: Array[4], 10: Array[4]}
 ajaxRequests.js:34
Object {0: Array[4], 2: Array[4], 4: Array[4], 6: Array[4], 8: Array[4], 10: Array[4]}
 ajaxRequests.js:34
Object {0: Array[4], 2: Array[4], 4: Array[4], 6: Array[4], 8: Array[4], 10: Array[4]}
 ajaxRequests.js:34

修改 我想我理解第一个问题发生的原因:第一个请求的响应被包含在[]中,因此被认为是一个数组

[["12650NZM KCG YYYNYNYYA","12650"," +KTK SMPRK K EXP ","H NIZAMUDDIN ","06:45","KACHEGUDA ","07:05","24:20","Y","Y","N","Y","N","Y","Y"],["12724NDLSHYB NYYYYYYYA","12724"," +A P EXPRESS  ","NEW DELHI ","17:30","HYDERABAD DECAN","19:50","26:20","Y","Y","Y","Y","Y","Y","Y"],["12722NZM HYB YYYYYYYYA","12722"," +DAKSHIN EXPRESS ","H NIZAMUDDIN ","23:00","HYDERABAD DECAN","05:00","30:00","Y","Y","Y","Y","Y","Y","Y"]]

第二类请求&#39;回复包含在{}:

{"0":[" 1"," 7- 8-2014","AVAILABLE 28","AVAILABLE 12"],"2":[" 2"," 9- 8-2014","RAC24\/RAC 22 ","GNWL25\/WL20"],"4":[" 3","10- 8-2014","AVAILABLE 127","AVAILABLE 35"],"6":[" 4","11- 8-2014","AVAILABLE 179","AVAILABLE 56"],"8":[" 5","12- 8-2014","AVAILABLE 143","RAC2\/RAC 2 "],"10":[" 6","14- 8-2014","AVAILABLE 39","GNWL25\/WL9"]}

我不知道为什么会这样,因为json_encode()在两种情况下都是作用于2D数组(通过遍历DOMNodeList构建,如果这有助于任何人理解它),但至少我现在知道了为什么JS对待它们的方式不同。
尽管如此,仍然不知道第二个问题。

**编辑2:**好的,所以我认为一个是从一个关联数组编码的,这就是导致问题的原因。仍然没有对第二个问题的答案

1 个答案:

答案 0 :(得分:0)

PHP数组可以编码为JS数组或JS对象。如果且仅当数组的键全部是数字,并且按顺序,并且从零开始,并且没有任何遗漏(您缺少奇数键),那么它将是一个数组。否则(&#34;稀疏&#34;数组)它将是一个对象。


对于你的第二个问题,我不确定,因为我不使用jQuery:p但是这里是我处理a&#34;当所有ajax的东西都完成后&#34;&#39; #34;一点代码:

var count = trains.length;
for (var i = 0; i < trains.length; i++) {
    console.log(trains[i][0]);
    requests.push($.ajax({
        url: './availability.php', 
        dataType: 'json',
        data: { 
            day: $('input[name*="day"]').val(),
            month: $('input[name*="month"]').val(),
            lccp_trndtl: trains[i][0]
        }
     }).done(function(data) {
            console.log(data);
            allData[i] = data;
            count--;
            if( count == 0) doSomethingElse(allData);
     });
}

// replace that `when.apply` thing with `doSomethingElse` definition