使用jQuery获取url并提取url段

Ton*_*yGW 7 javascript ajax url jquery

在具有类别列表的网页上,每个类别标题以此格式链接: 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
Run Code Online (Sandbox Code Playgroud)

Gir*_*ish 12

试试这个

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

更新答案:

this获取当前锚链接的用户对象见下文

$(this).attr('href')
Run Code Online (Sandbox Code Playgroud)


DJ_*_*lly 7

首先将URL拆分为段:

var segments = url.split( '/' );
var action = segments[3];
var id = segments[4];
Run Code Online (Sandbox Code Playgroud)

  • 这很简单,但请注意它应该是`varsegments = window.location.href.split('/');`。请参阅:[使用 JavaScript 获取当前 URL?](/sf/answers/72424971/) (2认同)