$ .ajax如果条件 [英] $.ajax if condition
问题描述
我无法使用以下语法在ajax中编写条件。
I failed to write a condition inside of ajax by using the following syntax.
var num = 1;
$.ajax({
type: "POST",
//condition starts
if (num === 1){
url: url1,
data: data1,
}else{
url: url2,
data: data2,
}
//condition finishes
success: success,
dataType: dataType
});
但这种方式有效。
var num = 1;
if(num === 1){
$.ajax({
type: "POST",
url: url1,
data: data1,
success: success,
dataType: dataType
});
}else{
$.ajax({
type: "POST",
url: url2,
data: data2,
success: success,
dataType: dataType
});
}
第二种方法不太适合重复我的代码。
是我的第一个错误语法的脚本?有人可以指出吗?谢谢
the 2nd method is not quite ideal as repeating my code. is my first script in a wrong syntax? Could someone please point out? thanks
推荐答案
是我的第一个错误语法的脚本?
is my first script in a wrong syntax?
是的,绝对的。您只是在对象文字的中间插入if-else-statement部分。你应该使用这样的东西:
Yes, absolutely. You were just inserting if-else-statement parts in the middle of an object literal. You should use something like this:
var params = {
type: "POST",
success: success,
dataType: dataType
};
if (num == 1) {
params.url = url1;
params.data = data1;
} else {
params.url = url2;
params.data = data2;
}
$.ajax(params);
或者如果你想内联它们,你可以使用运营商:
Or if you want to inline them, you can use the ternary operator:
$.ajax({
type: "POST",
url: (num == 1) ? url1 : url2,
data: (num == 1) ? data1 : data2,
success: success,
dataType: dataType
});
(如果你不想重复这个条件,把它的布尔结果存储在一个变量中)
(If you don't want to repeat the condition, store its boolean result in a variable)
这篇关于$ .ajax如果条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!