2012-08-27 60 views
1

我是jQuery AJAX的新手。我想建立書籤系統,像Twitter做(收藏夾)。我有很多鏈接。因此,爲每個鏈接編寫AJAX請求是沒有用的。這就是爲什麼我想爲所有鏈接使用一個請求腳本。許多鏈接的AJAX請求

比方說,我有聯繫的東西此鏈接:

<a href="#" id="1"><i class="icon-star-empty"></i></a> 
<a href="#" id="2"><i class="icon-star"></i></a> 
<a href="#" id="3"><i class="icon-star-empty"></i></a> 

所以我想寫AJAX請求時,用戶點擊這些網址的一個做這樣的事情。

if (class="icon-star-empty"){ 
    ajaxURL = "/insertBoomark" 
} else{ 
    //it means class=icon-start 
    ajaxURL = "/deleteBookmark" 
} 

$.ajax({ 
    url: ajaxURL, 
    type: "POST", 
    data: {id : linkID}, // I don't know how to get linkID too :(
    success: if class was icon-star empty then change it to icon-star-empty else change it to icon-star 
}); 

我知道這是不正確的語法。 我該如何解決這個問題?請幫助:(

在此先感謝。

+0

爲什麼你需要存儲用戶的書籤在服務器端?您可以在客戶端使用Cookie存儲用戶的偏好設置。 –

+0

我需要它的另一個原因。 – Jack

回答

1
$("i").on("click", function() { 

    if ($(this).hasClass("icon-star-empty")){ 
     ajaxURL = "/insertBoomark" 
    } else{ 
     //it means class=icon-start 
     ajaxURL = "/deleteBookmark" 
    } 

    var linkID = $(this).parent().prop("id"); 
    var obj = $(this); 

    $.ajax({ 
     url: ajaxURL, 
     type: "POST", 
     data: {id : linkID}, 
     success: function() { 
      obj.hasClass("icon-star") ? obj.removeClass("icon-star").addClass("icon-star-empty") : obj.removeClass("icon-star-empty").addClass("icon-star"); 
     } 
    }); 
}) 
+0

謝謝你的回答。 +1爲它:)現在它發送AJAX請求,並在服務器端進行更改,但它不會更改類名:(「icon-star-empty」不會更改爲「icon-star」:(我怎麼能解決這個問題? – Jack

+0

更新..如果不起作用 - 檢查你的Ajax成功被調用,因爲三元運算符工作正常 - http://jsfiddle.net/PGdrB/ –

+0

現在它的工作!非常感謝! – Jack

0

好吧,首先,class是在JavaScript保留名稱。

其次,如果你與jQuery.click功能做,那麼你可以這樣做$(this).attr('id')獲得ID。

同樣,對於成功的一部分,你似乎混淆了JavaScript的功能語法。你到底是想做什麼?

+0

我知道這是不正確的語法。我寫它只是爲了解釋我真正想要的。你能幫我請 – Jack

1

您也可以使用href屬性,並阻止jquery事件的默認操作。

HTML

<a href="page1" class="icon-star-empty"></a> 
<a href="page2" class="icon-star"></a> 
<a href="page3" class="icon-star-empty"></a> 

的JavaScript

$(function(){ 
     $(document).on('click','a',function(e){ 
      e.preventDefault(); //prevent default click action 
      var $this = $(this); // keeps "this" accessable 
      var ajaxURL = $this.attr('href'); // get the url from the "a" tag 
      $.ajax({ 
       url: ajaxURL, 
       type: "POST", 
       data: {id : linkID}, 
       success: function() { 
        if($this.hasClass("icon-star")) 
         $this.removeClass("icon-star").addClass("icon-star-empty"); 
        else 
         $this.removeClass("icon-star-empty").addClass("icon-star"); 
       } 
      }); 
     }); 
    }); 
0
$('a').click(function(){ 
    var _ajaxURL, 
    _self = $(this); 
    if($(this).hasClass('icon-star-empty')){ 
     _ajaxUrl = "/insertBookmark"; 
    }else{ 
     _ajaxUrl = "/deleteBookmark"; 
    } 
    $.ajax({ 
     url: _ajaxUrl, 
     type: 'POST', 
     data: {id : $(this).prop('id')}, 
     success: { 
      //I have no idea what you want to do right here. 
     } 
    }); 
});