如何使用javascript获取HTTP GET请求?
例如,如果我有权访问www.sample.com/div/a/dev.php?name=sample
如何获取name=sample
的GET请求以及name
sample
的值?
答案 0 :(得分:3)
Here is a fast way to get an object similar to the PHP $_GET array:
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = qs[i][1];
}
return result;
}
Usage:
var $_GET = get_query();
For the query string x=5&y&z=hello&x=6 this returns the object:
{
x: "6",
y: undefined,
z: "hello"
}
答案 1 :(得分:1)
window.location对象在这里可能会有用:
var parameter = window.location.search.replace( "?", "" ); // will return the GET parameter
var values = parameter.split("=");
console.log(values); // will return and array as ["name", "sample"]
答案 2 :(得分:0)
您可以使用location.href
获取完整网址,然后使用split
答案 3 :(得分:0)
构建URL字符串并使用jQuery get