23

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
        });

but this way works.

 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

4

7 回答 7

39

我的第一个脚本语法错误吗?

是的,一点没错。您只是在对象文字的中间插入 if-else-statement 部分。你应该使用这样的东西:

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);

或者如果你想内联它们,你可以使用三元运算符

$.ajax({
    type: "POST",
    url: (num == 1) ? url1 : url2,
    data: (num == 1) ? data1 : data2,
    success: success,
    dataType: dataType
});

(如果您不想重复条件,请将其布尔结果存储在变量中)

于 2013-02-07T23:07:11.337 回答
5

你可以这样做:

var num = 1, url, data;

if (num === 1) {
    url = url1;
    data = data1;
} else {
    url = url2;
    data = data2;
}

$.ajax({
    type: "POST",
    url: url,
    data: data,
    success: success,
    dataType: dataType
});
于 2013-02-07T23:06:41.827 回答
4

{大括号中的东西}是一个对象字面量。您可以在调用之前声明并修改它$.ajax

var options =
{
    type: "POST",
    url: url2,
    data: data2,
    success: success,
    dataType: dataType
};

if (num === 1) { options.url = url; options.data = data; }

$.ajax(options);
于 2013-02-07T23:10:05.280 回答
3

$.ajax接受一个常规的 JavaScript 对象,所以你可以分段填充它:

request = {type: "POST", success: success, dataType: dataType};
if(num == 1) {
    request.url = url1;
    request.data = data1;
} else {
    request.url = url2;
    request.data = data2;
}
$.ajax(request);
于 2013-02-07T23:09:09.697 回答
2

如果 url 和 data 非常简单,请尝试这种方式。

  var num = 1;
  $.ajax({
      type: "POST",
      url : (num==1? url1 : url2),
      data: (num==1? data1 : data2),
      success: success,
      dataType: dataType
    });
于 2013-02-07T23:08:40.300 回答
0

将条件放在 ajax 语句之前并在那里分配公共变量。

于 2013-02-07T23:06:07.057 回答
0

尝试这个:

var num = 1;
$.ajax({
    type: "POST",
    url: (num === 1 ? url1 : url2)
    data: (num === 1 ? data1 : data2)
    success: success,
    dataType: dataType
});

但正如其他人所提到的,最好只在 ajax 调用之外分配变量。

于 2013-02-07T23:09:54.437 回答