简体   繁体   中英

Get URL parameters through POST method and javascript

How would you extract the URL parameters in javascript through a POST method?

For example: localhost:8080/file.html/a/30/b/40

a and b would be keys while 30 and 40 would be the values for those keys

Thanks in advance!

Did you mean GET?

file.html?a=30&b=40

From this URL, you can get the parameters as follows:

var param = {};
var s = window.location.search.substring(1).split('&');
for (var i = 0; i < s.length; ++i) {
    var parts = s[i].split('=');
    param[parts[0]] = parts[1];
}
console.log(param);



EDIT:

The URL you provided doesn't have to do anything with POST, as far as I know, but if you can get it into a JavaScript variable, you can do this:

 var url = "file.html/a/30/b/40"; var param = {}; var parts = url.split("/"); for (var i = 1; i < parts.length; i += 2) { param[parts[i]] = parts[i+1]; } console.log(param); 

How about using a regular expression like this?

​var url = document.URL;                             // get the current URL
var matches = url.match(/.*\/a\/(\d+)\/b\/(\d+)/);  // match it with a regex
var a = matches[1];                                 // the "a" number (as string)
var b = matches[2];                                 // the "b" number (as string)

Note that the match method returns a list, the first element of which is the overall match with the remaining items being the captured elements, ie the two (\\d+) parts of the regex pattern. That's why this snippet uses matches[1] and matches[2] while ignoring matches[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM