if / else语句在.ajax中

时间:2012-02-18 08:08:45

标签: javascript jquery if-statement

假设我有这段代码通过ajax获取最新帖子:

  $.ajax({
    url: loadmore,
    data: {lastid: lastid,mode:'latest'},
    dataType: 'json',
    type: 'POST',
    timeout: 10000,
    success: function(json){
      //some code
    },
    error: function(jqXHR, textStatus, errorThrown){
      //some code
    }
  });

如何更改数据内容?这是我的尝试,但失败了。

  $.ajax({
    url: loadmore,
    if($('.postlist').hasClass('best'))
      data: {lastrank: lastrank,mode: 'best'},
    else
      data: {lastid: lastid,mode:'latest'},
    dataType: 'json',
    type: 'POST',
    timeout: 10000,
    success: function(json){
      //some code
    },
    error: function(jqXHR, textStatus, errorThrown){
      //some code
    }
  });

2 个答案:

答案 0 :(得分:5)

三元运营商:

 $.ajax({
    url: loadmore,
    data: ($('.postlist').hasClass('best') ?
      {lastrank: lastrank,mode: 'best'} :
      {lastid: lastid,mode:'latest'}),
    dataType: 'json',
    type: 'POST',
    timeout: 10000,
    success: function(json){
      //some code
    },
    error: function(jqXHR, textStatus, errorThrown){
      //some code
    }
  });

答案 1 :(得分:4)

您可以使用?:(三元运算符)运算符:

data: ($('.postlist').hasClass('best')) ?
      {lastrank: lastrank,mode: 'best'} : 
      {lastid: lastid,mode:'latest'},