jquery nested ajax calls formatting

早过忘川 提交于 2019-12-17 22:40:05

问题


I have a requirement to make 6 ajax calls in succession based on data from the previous call. I am nesting each call in the success of the previous call. my question is what are some good ways to format the code so that it doesnt end up a million rows across my editor?

 $.ajax({
                type: "POST",
                url: "someScript/someScript.php",
                data: form + "&func=build",
                success: function (result) {
                 if (result == "ok")
                 {
                   $.ajax({
                   type: "POST",
                   url: "someScript/someScript.php",
                   data: form + "&func=someOtherFunc",
                   success: function (result) {
                        if (result == "ok")
                        {
                          $.ajax({
                           type: "POST",
                           url: "someScript/someScript.php",
                           data: form + "&func=someOtherFunc",
                           success: function (result) {
                           if (result == "ok")
                           {
                             .....and so on
                           }
                           })
                         }
                      })
                    })
                   }
                 })

ignore brackets, syntax isnt important for this question.


回答1:


You can do something like this

function ajaxCall1(){
    $.ajax({
        success: function(){
            ajaxCall2();
        }
    });
}
function ajaxCall2(){
    $.ajax({
        success: function(){
            ajaxCall3();
        }
    });
}
function ajaxCall3(){
    $.ajax({
        success: function(){
            ajaxCall4();
        }
    });
}



回答2:


You can do something like this:

var url = '/echo/json/';
var dados = {acao: acao,codigo: null};

function funcao1(json,data)
    $.post(url, data, function(json){
        return json;
    }).fail(function() {
        alert("deu erro");
    });
}

alert(funcao1(funcao1(funcao1(),{id:"id1"}),{id:"id1"}));

You can add the url and other data as parameters.

Another idea is to create a function that receive an array like this:

[{url:'url1', cb:function1},{url:'url2',cb:function2}]

This could be a recursive function that delete an item every calls end.



来源:https://stackoverflow.com/questions/22233650/jquery-nested-ajax-calls-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!