2012-02-18 84 views
0

內/ else語句比方說,我有這樣的代碼獲得通過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 
    } 
    }); 

回答

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

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

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