如何带参数访问URL

3

如何在JavaScript中完成以下操作?

使用附加参数向URL进行GET调用,例如:

我想要对http://test进行GET调用,并携带参数myid = 5。

谢谢, Boots

5个回答

3

尝试类似以下的代码:

location.replace('http://test.com/sometest.html?myid=5&someotherid=6');

或者
location.href = 'http://test.com/sometest.html?myid=5&someotherid=6';

2
如果你的意思是通过“对URL进行GET调用”,改变当前位置到特定的URL,那么你需要将新的URL赋值给“location”变量即可。
var newUrl = "http://test";
window.location = newUrl;

如果您想通过添加一些查询参数来构建URL,可以这样做:
newUrl += "?myid=" + myid;

此外,您可以使用一个函数将参数映射到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;
}

然后您可以将其用作:
window.location = generateUrl("http://test",{ 
    myid: 1,
    otherParameter: "other param value"
});  

注意:此功能仅适用于参数对象中的整数/布尔/字符串变量。不能以此方式使用对象和数组。


0

如果你只想调用它,而且不需要跳转到它,可以使用 AJAX 请求:

$.ajax({
    url: 'http://test/?myid=5'
});

这里使用jQuery。但是互联网上有足够多的非jQuery示例。


0

你只需在查询字符串中正常包含它:http://test?myid=5&otherarg=3


0
var myid = 5;
window.location = "http://test?myid=" + myid;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接