Using jQuery to get url and extract url segments

On a web page that has a list of categories, and the name of each category are related in this format: http://localhost/admin/category/unpublish/2

I wrote the following js code trying to grab the url and render segments (action) and "2" (id) and you need to send a 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 
+7
javascript jquery url ajax
source share
3 answers

try it

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

Update answer:

User this object to get the current link binding below

 $(this).attr('href') 
+10
source share

First, divide the URL into segments:

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

I think you can use split . Then you can have an array with which you can get the action and identifier.

+1
source share

All Articles