[英]Making a JQuery ajax request conditional
如果不满足某些前提条件,我想跳过所有这段代码,但是我也想在函数中的括号之间移动所有代码。 可以吗 我不了解此语法的工作原理。
$.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');
}
});
将$.ajax
调用放入函数中,然后将对函数的调用包装在条件表达式中:
function makeRequest(){
$.ajax( ... )
}
if ( some_condition ){
makeRequest();
}
请记住,您正在AJAX回调中使用一些变量(即已canceled
变量)。 您必须使该变量对函数可用。
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
将自动接收成功函数接收的所有参数。
尝试这个:
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);
}
看一下这个样本:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.