以下是完整的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)打印整个数组。通过按钮调用脚本。
发布于 2018-04-13 12:53:08
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 milisecondshttps://stackoverflow.com/questions/49817122
复制相似问题