javascript – 使用jQuery获取url并提取url段

在具有类别列表的网页上,每个类别标题都以以下格式链接:http:// localhost / admin / category / unpublish / 2

我编写了以下js代码,尝试捕获url和段’unpublish'(动作)和’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

试试这个

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

更新答案:

使用此对象获取当前锚点链接,如下所示

$(this).attr('href')

翻译自:https://stackoverflow.com/questions/24481918/using-jquery-to-get-url-and-extract-url-segments