Ajax returns 只有字符串化数组的第一个索引到 Spring 控制器

Ajax returns only first index of stringified array to the Spring controller

这是完整的 JS 代码:

function getPoolsData(){
$.getJSON('../json/data.json', function(data) {

var date_from = new Date();
console.log(date_from);
var pools_hashrates = [{"date_from" : date_from}];

data.pools.forEach(function(pool){

var api_url = pool.api;
var poolName = pool.name;

if(pool.type == "forknote"){

    $.getJSON(api_url + 'stats', function(data) {

            var poolHashrate = data.pool.hashrate;

            pools_hashrates.push({"poolName" : poolName, "hashrate" : poolHashrate});

            console.log("Pool name: " + poolName + " Pool hashrate: " + parseInt(poolHashrate));
    });
}
else{
    $.getJSON(api_url + 'pool/stats', function(data) {

            var poolHashrate = data.pool_statistics.hashRate;

            console.log("Pool name: " + poolName + " Pool hashrate: " + parseInt(poolHashrate));

            pools_hashrates.push({"poolName" : poolName, "hashrate" : poolHashrate});

    });
}

});

console.log(pools_hashrates);

$.ajax({
  type: "POST",
  contentType : 'application/json; charset=utf-8',
  dataType : 'json',
  url: "/save",
  data: JSON.stringify(pools_hashrates),
  success :function(result) {
      console.log("Success!");
 }
});

});
}

控制器方法如下:

@RequestMapping("/save")
public @ResponseBody String getPoolsData(@RequestBody String string){

    System.out.println("Triggered: " + string);
    return "Success mvc";
}

控制器输出:

Triggered: [{"date_from":"2018-04-13T11:05:00.652Z"}]

问题是,只有数组的第一个索引被发送到控制器,而数组的长度约为 20。 console.log(pools_hashrates) 打印整个数组。通过按钮调用脚本。

Ajax 调用是异步的,这意味着它将同时触发所有 3 个,对 getPoolsData 的调用不会等待 get 完成,您需要设置 ajax 异步调用。

像这样

$.ajaxSetup({
    async: false
});

请注意,这会将所有 ajax 调用设置为异步,更好的做法是重写您的调用

$.ajax({
    url: "...",
    type: "GET",
    data: ...,
    async: false
});

只进行异步调用

或者您可以使用 setInterval 继续检查是否 jQuery.active == 0

jQuery.active == 0 // this tells you if you have active ajax calls

如果是这样的话

var myTimer = setInterval((function(){ 
    if (jQuery.active == 0){
        $.ajax({
            type: "POST",
            contentType : 'application/json; charset=utf-8',
            dataType : 'json',
            url: "/save",
            data: JSON.stringify(pools_hashrates),
            success :function(result) {
                console.log("Success!");
            }
        });
        clearInterval(myTimer); // stop the interval once you the get calls finished and you send the ajax call
    }
}, 1000)); // 1000 is the interval at which to check set in miliseconds