javascript 如何使用参数转到 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6179558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to go to URL with parameters
提问by user776635
How would i do the following in javascript?
我将如何在 javascript 中执行以下操作?
Do a GET
call to a URL, with additional parameter .e.g.
做一个GET
呼叫到一个URL,与附加参数.eg
I want to do GET
to http://testwith parameter myid = 5.
我想用参数 myid = 5GET
对http://test做。
Thanks, Boots
谢谢,靴子
回答by KooiInc
try something like:
尝试类似:
location.replace('http://test.com/sometest.html?myid=5&someotherid=6');
or
或者
location.href = 'http://test.com/sometest.html?myid=5&someotherid=6';
回答by gion_13
If by "Do a 'GET' call to a url"you mean to change the current location to a certain url, all you have to do is assign the new url to the location
variable:
如果“对 url 进行 'GET' 调用”是指将当前位置更改为某个 url,则您所要做的就是将新 url 分配给location
变量:
var newUrl = "http://test";
window.location = newUrl;
If you want to construct the url by adding some query parameters, you can do :
如果你想通过添加一些查询参数来构造 url,你可以这样做:
newUrl += "?myid=" + myid;
In addition, you can use a function to map the parameters to the url :
此外,您可以使用函数将参数映射到 url :
function generateUrl(url, params) {
var i = 0, key;
for (key in params) {
if (i === 0) {
url += "?";
} else {
url += "&";
}
url += key;
url += '=';
url += params[key];
i++;
}
return url;
}
And then you could use it as :
然后你可以将它用作:
window.location = generateUrl("http://test",{
myid: 1,
otherParameter: "other param value"
});
obs: this function only works for int/bool/string variables in the params object. Objects and arrays cannot be used in this form.
obs:此函数仅适用于 params 对象中的 int/bool/string 变量。不能以这种形式使用对象和数组。
回答by Niklas
var myid = 5;
window.location = "http://test?myid=" + myid;
回答by seymar
If you only want to call it. And don't go to it: Use an AJAX request:
如果你只想调用它。而且不要去它:使用AJAX请求:
$.ajax({
url: 'http://test/?myid=5'
});
Here in jQuery. But there are enough non-jQuery examples on the internet.
在 jQuery 中。但是互联网上有足够多的非 jQuery 示例。
回答by yan
You'd just include it normally in the query string: http://test?myid=5&otherarg=3
您只需将它通常包含在查询字符串中: http://test?myid=5&otherarg=3