【问题标题】:I am having an issue while calling json multiple time using for loop我在使用 for 循环多次调用 json 时遇到问题
【发布时间】:2017-07-22 01:46:41
【问题描述】:
for(var j = 0; j < tempArray.length; j ++){
 $.getJSON('http://localhost:8080/predict', tempArray[j])
    .fail(function(data,textStatus, error) {
      Probability = data.responseText;
      console.error("getJSON failed, status: " + textStatus + ", error: "+error);
    })

    .done(function(data) {
      console.log(data);
      Probability = data.classProbabilities[0];
      Array.prototype.push.call(resultPercentage, Probability);
    });
}
console.log(resultPercentage);

tempArray 是一个包含 10 个对象的数组。我正在使用 for 循环将该数组传递给 json。
resultPercentage 在一个数组中打印 10 个不同的结果。
每当我使用 for 循环调用该 Json 时,它会不断更改该数组中结果的顺序。

【问题讨论】:

  • 您能否澄清问题所在...既然您有 10 个预期结果。你知道.get() 是异步的,对吧?
  • @LouysPatriceBessette:是的,那么我怎样才能获得同步的结果?每次“resultPercentage”给我一个随机序列数组的结果。
  • 我认为几乎不可能同时“订购”多个 ajax 请求发送到服务器。治疗顺序取决于服务器。你应该做的是发送一个“标识符”和数据,并设法在响应中取回这个标识符。然后用它来“重新排序”它们。 -- 喜欢... 改为发送一个对象:{data:tempArray[j],id:j}
  • @LouysPatriceBessette:好的,让我试试
  • @LouysPatriceBessette:如何在我的程序中传递该对象?

标签: javascript jquery json ajax for-loop


【解决方案1】:

我遇到了类似的问题,我做了这样的事情:

    $.each( array, function( key, value ) {
      $.ajax({
        url: "http://localhost:8080/example",
        data: JSON.stringify(value),
        async:false,
        success:something,
       fail:something
      });
   });

您也可以使用 for 循环尝试此操作。 async:false 将阻止它异步运行。

【讨论】:

  • 这看起来很有希望。让我试试!
  • 工作!谢谢:)
【解决方案2】:

做这样的事情。注意:您不能在循环内运行函数。试试看,如果有效,请告诉我们。如果没有,请提供您的意图,您实际上想要做什么。

var tempArray = [];

for(var j = 0; j < tempArray.length; j++){  
                   $.getJSON('http://localhost:8080/predict', tempArray[j])
                    .fail(first)
                    .done(second);
    }
     console.log(resultPercentage);

function first(data, textStatus, error) {
                        Probability = data.responseText;
                        console.error("getJSON failed, status: " + textStatus + ", error: "+error);
                    }

function second(data) {
                    console.log(data);
                    Probability = data.classProbabilities[0];
                    Array.prototype.push.call(resultPercentage, Probability);
                } 

【讨论】:

  • 假设,在我的程序中 resultPercentage 输出是 {15,88,30,55,7} 的数组。如果我再次运行我的程序,我会得到 {30,55,7,15,88}。所以顺序是不断变化的。我希望 tempArray[0] 在第一个位置回答, tempArray[1] 在输出数组的第二个位置回答,依此类推。
【解决方案3】:

就像在cmets中说的那样,多个ajax resquest同时发送几乎(我们说的是微秒)的处理顺序取决于服务器。

我不知道服务器如何管理它。
但是肯定,不能保证它们会按顺序处理。

我只能用理论上的建议来回答...
因为我不知道http://localhost:8080/predict 做了什么。
我什至不知道这是不是 PHP。



所以这只是我会尝试应用的原则...
我从来没有尝试过......顺便说一句。 ;)
我要做的第一件事是将j 循环计数器作为请求id 传递。
然后,我将使用Ajax Global Events 来处理响应,而不是循环中的.fail().done()
这会将for 循环缩短为:
for(var j = 0; j < tempArray.length; j ++){
 $.getJSON('http://localhost:8080/predict', '{data:tempArray[j],id:j}');   // Pass the array AND an id
}

现在,在 http://localhost:8080/predict,获取数据并做你的事情。
保留 id 以在 json 响应中重新注入。

<?php
$data = $_REQUEST['data'];
$id = $_REQUEST['id'];

// Do your stuff with $data...
// ...

// Add the passed id to the json actually produced:
echo '{id:' . $id . ', classProbabilities:[0.90], color:"blue", somethingElse:"Other data"}';

?>

使用 Ajax 全局事件可以使用一些计数器。
在尝试显示结果之前确保所有请求都已完成很有用。
即使某些请求失败,您也可以显示成功请求的结果。

// Counters.
var completed_Ajax = 0;
var error_Ajax = 0;
var success_Ajax = 0;

// An array to get the resquest response order
var responseOrder = [];

// An array to have the resquest responses reordered (final result)
var resultPercentageOrdered = [];


// Error handler
$.ajaxError(function(request, status, error){
  error_Ajax++;
  console.log("Error #"+error_Ajax+":\n"+error);
});

// Sucess handler
$.ajaxSuccess(function(data){
  success_Ajax++;

  // Handle the data (your code untouched)
  console.log(data);
  Probability = data.classProbabilities[0];
  Array.prototype.push.call(resultPercentage, Probability);

  // Push the received id in array.
  responseOrder.push(data.id);

  if( success_Ajax == tempArray.length ){
    console.log("All resquests succeded.");
  }
});

// Completed request handler
$.ajaxComplete(function(){
  completed_Ajax++;

  if( completed_Ajax == tempArray.length ){
    console.log("All resquests done.");
  }

  if( (error_Ajax + success_Ajax) == tempArray.length ){  // Even if there are errors... Show results when all resquests completed.

    // The result before ordering.
    console.log(JSON.stringify(resultPercentage));

    // Just for fun, show the resquest processing order
    console.log(JSON.stringify(responseOrder));

    // Reordering the results, using responseOrder
    //
    for(i=0;i<success_Ajax;i++){
      var index = responseOrder.indexOf(i);
      resultPercentageOrdered.push(resultPercentage[index]);
    }

    // Show them in console.
    console.log(JSON.stringify(resultPercentageOrdered));

    // Use this result array here.
    // ...
    // ...
  }
});

【讨论】:

  • 感谢您的解决方案。让我尝试使用它,我会尽快通知您:)
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
相关资源
最近更新 更多