2013-10-10 66 views
0

我想刪除一個沒有頁面刷新的鏈接,我想jQuery捕獲併發送http請求到一個特定的URL刪除。但是,爲了這個工作,我需要能夠使用jQuery/Ajax來獲取點擊鏈接並將其作爲http請求發送。如何檢查鏈接是否使用AJAX/jQuery點擊

這是鏈接:

<a href='http://example.com/delete.php?id=243'> <span class='delete'>delete this</span> </a> 

現在,這是jQuery和阿賈克斯樹枝模板來獲得點擊的鏈接和發送的HttpRequest與id來delete.php,這樣ID可以被刪除。

$(document).ready(function() { 
     $(".delete").click(function(){ 
      $.ajax({ 
       type: "GET", 
       url: "{{ path('http://example.com/delete.php?id=243'}}", 
       cache: "false", 
       dataType: "html", 
       success: function(result){ 
        $(".success").append(result); 
       } 
      }); 
     }); 

     } 

但上述功能只會讓頁面在點擊時導航到鏈接。

+2

'點擊(函數(E){e.preventDefault();' - 點擊函數將Event對象作爲第一個參數,調用它的方法'preventDefault'來停止瀏覽器跟隨鏈接。 – SmokeyPHP

回答

2

使用jQuery的preventDefault()阻止鏈接的默認行爲。

有:

<a class='delete' href='http://site.com/delete.php?id=243'> delete this </a> 

嘗試:

$(".delete").click(function(e){ 
    e.preventDefault(); 
    $.ajax({ 
     type: "GET", 
     url: "{{ path('http://site.com/delete.php?id=243'}}", 
     cache: "false", 
     dataType: "html", 
     success: function(result){ 
      $(".success").append(result); 
     } 
    }); 
}); 
2

你需要preventDefault

$(".delete").click(function(e){ 
    e.preventDefault() 
    $.ajax({ 
    .. 
+0

仍然重定向到指定的路徑。 – ANW

+0

@piosoiq您可以將'delete'類添加到錨標記並刪除跨度?如果沒有,你需要在anchor標籤上設置preventDefault或者添加'e.stopPropagation();' – marteljn

+0

如果你感興趣的話,可以在這裏用'+ 100'賞金相關http://stackoverflow.com/questions/19355562/how-to- add-ajax-capabilites-to-symfony – ANW

2

我不知道如果我得到你在這裏,但是這可以幫助你:http://api.jquery.com/event.preventDefault/

$("a").click(function(event) { 
    event.preventDefault(); 

    //your code 
} 
+0

謝謝,但不適合我。我仍然重定向到指定的路徑 – ANW

+0

你需要href屬性中的完整url嗎?你可以使用錨點,所以用戶不會被重定向。編輯:或者根本不使用標籤。 – TheFrozenOne

+0

如果你感興趣的話,在這裏用'+ 100'賞金相關http://stackoverflow.com/questions/19355562/how-to-add-ajax-capabilites-to-symfony – ANW