最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - using jQuery to get url and extract url segments - Stack Overflow

programmeradmin2浏览0评论

On a webpage that has a list of categories, and each category title is linked in this format: http://localhost/admin/category/unpublish/2

I wrote the following js code, trying to capture the url and the segments 'unpublish' (action) and '2' (id), and need to send the request to 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

On a webpage that has a list of categories, and each category title is linked in this format: http://localhost/admin/category/unpublish/2

I wrote the following js code, trying to capture the url and the segments 'unpublish' (action) and '2' (id), and need to send the request to 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
Share Improve this question edited Jan 22, 2018 at 10:12 Mosh Feu 29.3k18 gold badges93 silver badges141 bronze badges asked Jun 30, 2014 at 1:36 TonyWTonyW 18.9k42 gold badges116 silver badges190 bronze badges 1
  • This question might be useful. stackoverflow.com/questions/406192/… – phpLearner Commented Jun 30, 2014 at 1:41
Add a comment  | 

3 Answers 3

Reset to default 13

Try this

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

Update Answer:

User this object to get current anchor link see below

$(this).attr('href')

Split the URL into segments first:

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

I think you can use split. Then you can have an array to work with from which you can get the action and id.

发布评论

评论列表(0)

  1. 暂无评论