最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ifelse statement inside .ajax - Stack Overflow

programmeradmin2浏览0评论

Let's say I have this code which gets the latest posts via 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
    }
  });

How do I change the content of the data? Here's my try but something failed.

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

Let's say I have this code which gets the latest posts via 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
    }
  });

How do I change the content of the data? Here's my try but something failed.

  $.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
    }
  });
Share Improve this question asked Feb 18, 2012 at 8:08 Jürgen PaulJürgen Paul 15k28 gold badges96 silver badges136 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Ternary operator:

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

You could use the ?: (ternary operator) operator:

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

评论列表(0)

  1. 暂无评论