weixin_33691817 2015-06-01 11:15 采纳率: 0%
浏览 12

Ajax循环调用

I know there are lot of question regarding this but still I am unable to find a proper answer which makes my code run properly.

I have one function defined to call ajax which I cannot change due to security issue. This is how I call that function

var JsonIQDetails = JSON.stringify(input);//Some input

//pram 1:MethodUrl, 2:JsonObject, 3:ReturnType, 4:SuccessCallBackFunction
InvokeAjaxCall(Url, JsonIQDetails, "json", Success); 

I have array of objects (more than 500). Since JSON is getting very long so I am unable to make ajax call. Again due to security issue I can't change config file too. So JSON length cannot be increased.

I am dividing the array into small chunks of 100 and calling the method

for (i = 0, j = mainObject.length; i < j; i += chunk) {
    var newSubObject = mainObject.slice(i, i + chunk);
    InvokeAjaxCall(Url, newSubObject, "json", Success);

    function Success(data) {
        if (!data) {
            alert("Failed");
            break;
        }
    }
}

Its moving without completing the for loop and executing the next code. So I want first it to complete the for loop (Probably asynchronous)

Thanks in Advance..!!!

  • 写回答

1条回答 默认 最新

  • weixin_33743703 2015-06-01 11:26
    关注

    Ajax is by default Asynchronous, so you pretty much need to invoke the next part of your ajax call in your success function. Here is a recursive loop that takes care of that.

    var ajaxRecursive = function(i, j, c){
        if(i < j){
           var newSubObject = mainObject.slice(i, i + chunk);
           InvokeAjaxCall(Url, newSubObject , "json", function(data){
               //do stuff with data
               ajaxRecursive(i+=chunk, j,chunk);
           });
        }
    }
    
    
    ajaxRecursive(0, mainObject.length, chunk);
    

    Supposing that the other variables within ajaxRecursive are defined globally.

    Update description:

    • You can get rid of your "success" function and just create it annonymously.
    评论

报告相同问题?

悬赏问题

  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”