首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ajax只将字符串化数组的第一个索引返回给Spring控制器

Ajax只将字符串化数组的第一个索引返回给Spring控制器
EN

Stack Overflow用户
提问于 2018-04-13 12:34:12
回答 1查看 39关注 0票数 0

以下是完整的JS代码:

代码语言:javascript
复制
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!");
 }
});

});
}

以下是控制器方法:

代码语言:javascript
复制
@RequestMapping("/save")
public @ResponseBody String getPoolsData(@RequestBody String string){

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

以及控制器输出:

代码语言:javascript
复制
Triggered: [{"date_from":"2018-04-13T11:05:00.652Z"}]

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-13 12:53:08

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

像这样

代码语言:javascript
复制
$.ajaxSetup({
    async: false
});

请注意,这将将所有ajax调用设置为异步调用,最好将调用重写为异步调用。

代码语言:javascript
复制
$.ajax({
    url: "...",
    type: "GET",
    data: ...,
    async: false
});

只进行那些异步调用

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

代码语言:javascript
复制
jQuery.active == 0 // this tells you if you have active ajax calls

如果是这样的话

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49817122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档