[英]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調用是異步的,這意味着它將同時觸發所有三個調用,對getPoolsData的調用不會等待獲取完成,您需要將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.