2012-05-29 60 views
0

我的問題很簡單。這是我的代碼,我發現它們是兩個類似的,我該如何改進/縮短這段代碼?如何改進/縮短這2個類似的Ajax請求?

我發現它們在許多方面都很相似,這就是爲什麼我在這裏問。

這是我的代碼和任何幫助表示讚賞。

$(".follow-link").click(function(event) { 
    event.preventDefault(); 
    var therel = $(this).attr('rel'); 
    var followID = $(this).attr('rel').replace(/[^0-9]/g, ''); 
    var thisfollow = $(this); 
    $.ajax({ 
     url: '/ajax/follow.php', 
     type: 'POST', 
     data: {followwho : followID}, 
     dataType: 'json', 
     success: function(data){ 
      if (data.status) { 
       $('a[rel="' + therel + '"]').hide(); 
       $('a[rel="' + therel + '"]').parent().children('.unfollow-link').fadeIn(); 
      } 
     } 
    }); 
}); 

$(".unfollow-link").click(function(event) { 
    event.preventDefault(); 
    var therel = $(this).attr('rel'); 
    var followID = $(this).attr('rel').replace(/[^0-9]/g, ''); 
    var thisfollow = $(this); 
    $.ajax({ 
     url: '/ajax/unfollow.php', 
     type: 'POST', 
     data: {followwho : followID}, 
     dataType: 'json', 
     success: function(data){ 
      if (data.status) { 
       $('a[rel="' + therel + '"]').hide(); 
       $('a[rel="' + therel + '"]').parent().children('.follow-link').fadeIn(); 
      } 
     } 
    }); 
}); 

回答

3

讓一個共同的功能,並做了一些簡化清理工作在功能:

function followAjax(event, sel, phpurl) { 
    event.preventDefault(); 
    var thisfollow = $(this); 
    var therel = thisfollow.attr('rel'); 
    var followID = therel.replace(/[^0-9]/g, ''); 
    $.ajax({ 
     url: phpurl, 
     type: 'POST', 
     data: {followwho : followID}, 
     dataType: 'json', 
     success: function(data){ 
      if (data.status) { 
       $('a[rel="' + therel + '"]').hide().parent().children(sel).fadeIn(); 
      } 
     } 
    }); 
} 

$(".unfollow-link").click(function(event) { 
    followAjax.call(this, event, ".follow-link", '/ajax/unfollow.php') 
}); 
$(".follow-link").click(function(event) { 
    followAjax.call(this, event, ".unfollow-link", '/ajax/follow.php') 
}); 
+0

你也應該把url作爲參數。你有它編碼爲'/ajax/unfollow.php' – Steve

+0

@Steve - 好點 - 我沒有看到這種差異。固定。 – jfriend00

0

您可以使用相同的功能,在這兩個處理程序,查找this.className(或使用jQuery:$(this).hasClass)和做那麼適當的行動。或者你使用兩個函數,在閉包中生成它們:

$(".follow-link").click(makeHandler("follow")); 
$(".unfollow-link").click(makeHandler("unfollow")); 

function makeHandler(action) { 
    return function(event) { 
     event.preventDefault(); 
     var therel = $(this).attr('rel'); 
     var followID = $(this).attr('rel').replace(/[^0-9]/g, ''); 
     var thisfollow = $(this); 
     $.ajax({ 
      url: '/ajax/'+action+'.php', 
      type: 'POST', 
      data: {followwho : followID}, 
      dataType: 'json', 
      success: function(data){ 
       // no need to ask for data.status 
       $('a[rel="' + therel + '"]').hide(); 
       $('a[rel="' + therel + '"]').parent().children(action=="follow" 
        ? '.unfollow-link' 
        : '.follow-link' 
       ).fadeIn(); 
      } 
     }); 
    }; 
}