Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - $.ajax if condition

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

is my first script in a wrong syntax?

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...