如果不满足某些前提条件,我想跳过所有这段代码,但我也希望在函数中的括号之间移动所有代码。是允许的吗?我不明白这种语法是如何工作的。
$.ajax({
type: "POST",
url: urlAppend,
data: JSON.stringify(xxx),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: false,
success: function (result) {
if (canceled) {
return;
}
//Long code
}
//Long code 2
},
error: function (request, error) {
alert('ppp');
}
});
答案 0 :(得分:3)
将$.ajax
调用放入函数中,然后将调用包装在条件表达式中:
function makeRequest(){
$.ajax( ... )
}
if ( some_condition ){
makeRequest();
}
请记住,您在AJAX回调中使用了一些变量(即canceled
变量)。您必须使该变量可用于该函数。
答案 1 :(得分:1)
function doComplexStuff(){
}
$.ajax({
type: "POST",
url: urlAppend,
data: JSON.stringify(xxx),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: false,
success: doComplexStuff,
error: function (request, error) {
alert('ppp');
}
});
doComplexStuff
将自动接收成功函数接收的所有参数。
答案 2 :(得分:1)
试试这个:
function runAjax(params){
$.ajax({
type: params["post"],
url: params["url"],
data: params["data"],
contentType: params["content_type"],
dataType: params["json"],
processdata: params["process_bool"],
success: function (result) {
if (params["canceled"]) {
return;
}
//Long code
}
//Long code 2
},
error: function (request, error) {
alert('ppp');
}
});
}
if(condition){
var options = {
//set options here
};
runAjax(options);
}
答案 3 :(得分:1)
看一下这个样本:
function callAjax(condition) {
if (condition) {
$.ajax({
type: "POST",
url: urlAppend,
data: JSON.stringify(xxx),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: false,
success: function (result) {
if (canceled) {
return;
}
//Long code
}
//Long code 2
},
error: function (request, error) {
alert('ppp');
}
});
}
}
// Somewhere in your code
callAjax(condition);