jQuery jquery嵌套ajax调用格式化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22233650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery nested ajax calls formatting
提问by bart2puck
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?
我需要根据上一次调用的数据连续进行 6 次 ajax 调用。我在上一个调用的成功中嵌套每个调用。我的问题是有什么好方法可以格式化代码,以便它不会在我的编辑器中出现一百万行?
$.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.
忽略括号,语法对于这个问题并不重要。
回答by Rimpy
You can do something like this
你可以做这样的事情
function ajaxCall1(){
$.ajax({
success: function(){
ajaxCall2();
}
});
}
function ajaxCall2(){
$.ajax({
success: function(){
ajaxCall3();
}
});
}
function ajaxCall3(){
$.ajax({
success: function(){
ajaxCall4();
}
});
}
回答by Onaiggac
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.
您可以添加 url 和其他数据作为参数。
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.
这可能是一个递归函数,每次调用结束时都会删除一个项目。