2014-06-30 22 views
7

在具有類別列表的網頁,每個類別標題鏈接的格式爲:http://localhost/admin/category/unpublish/2使用jQuery獲取URL和提取URL段

我寫了下面的js代碼,試圖捕捉的網址和段 '不發佈'(動作)和 '2'(ID),並且需要將請求發送到http://localhost/admin/category

$('#statusChanges a').click(function(evt) { // use the click event of hyperlinks 
    evt.preventDefault(); 
    var url = $(location).attr('href'); 
    // var action = url.segment(3); /*JS console complains that url.segment() method undefined! */ 
    // var id = url.segment(4); 
    $.ajax({ 
    type: "GET", 
    url: $(location).attr('href'), 
    dat: '', 
    /* do I need to fill the data with json data: {"action": "unpublish, "id": 2 } ? but I don't know how to get the segments */ 
    success: function(data) { 
     $('.statusSuccess').text('success!'); 
    }, 
    error: function(data) { 
     $('.statusSuccess').text('error!'); 
    } 
    }); 
}); // end of status change 
+0

此問題可能會有幫助。 http://stackoverflow.com/questions/406192/how-to-get-the-current-url-in-javascript/16602140#16602140 – phpLearner

回答

10

試試這個

var url = $(location).attr('href').split("/").splice(0, 5).join("/"); 

更新答:

用戶this對象來獲取當前錨鏈接見下文

$(this).attr('href') 
+0

我發現$(location).attr('href')給了我當前的url,但我想獲取標記的網址。謝謝 – TonyGW

+0

@TonyGW,試試'''當前網址'$(this).attr(「href」)'; – Girish

+0

所有權利,所以這給了我在hyerlink上正確的URL:var url = $(this).attr('href');感謝幫助! – TonyGW

7

拆分的URL成段第一:

var segments = url.split('/'); 
var action = segments[3]; 
var id = segments[4]; 
+0

這很簡單,但請注意,它應該是'var segments = window.location。 href.split('/');'。請參閱:[使用JavaScript獲取當前URL?](https://stackoverflow.com/a/1034642/3416774) – Ooker

1

我認爲你可以使用split。然後你可以有一個數組來處理從中你可以得到的動作和ID。