使用 Javascript 创建并转到 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5418536/
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
Create and go to url with Javascript
提问by Mike James
I want to be able to produce a URL based on certain properties and then go to the new URL in javascript.
我希望能够根据某些属性生成一个 URL,然后在 javascript 中转到新的 URL。
Here is what I have so far:
这是我到目前为止所拥有的:
triggerNumber = document.findcontrol(txtTrigNo).text;
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber
How do I navigate to the new URL?
如何导航到新 URL?
回答by Hossein
Simply try:
只需尝试:
window.location = url;
But before trying to do that, you have to make sure the page at the address "http://" + hostAddress "/" + triggerNumberexists. For example by putting valid triggerNumbers in an array and check if it exists or not. So:
但在尝试这样做之前,您必须确保地址为“http://”+hostAddress“/”+triggerNumber 的页面存在。例如,通过将有效的 triggerNumbers 放入数组并检查它是否存在。所以:
//Not sure if at the end it should be .text or .value or .value()
triggerNumber = document.findcontrol(txtTrigNo).text;
var validTriggers = [123, 456, 789];
if (validTriggers.indexOf(parseInt(triggerNumber)) == -1) {
alert("Invalid trigger number");
} else {
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber;
}
Finally, if the destination is a server-side page (php, asp, etc), the address usually looks like this:
最后,如果目标是服务器端页面(php、asp 等),则地址通常如下所示:
"http://" + hostAddress "/trigger.php?id=" + triggerNumber;
but you'd better use form
s for this.
但你最好form
为此使用s 。
Edit:As Cerbrus suggested, validating the values with javascript is a good way to tell the user about his errors before navigating away from the page. But to make sure the correct data is sent to server, it is important to do the validation in the server-side code, too.
编辑:正如 Cerbrus 所建议的,在离开页面之前,使用 javascript 验证值是告诉用户他的错误的好方法。但是为了确保将正确的数据发送到服务器,在服务器端代码中进行验证也很重要。
In this example, in case of an invalid trigger number the user may finally see a 404 error; but with sensitive information worse things can happen.
在这个例子中,如果触发器编号无效,用户最终可能会看到 404 错误;但是对于敏感信息,更糟糕的事情可能会发生。
回答by Shadow Wizard is Ear For You
What you need is:
你需要的是:
document.location.href = url;
After you have the URL in the url
variable.
在url
变量中有 URL 之后。
To get value of input element have:
要获取输入元素的值,请执行以下操作:
var triggerNumber = document.getElementById("txtTrigNo").value;
回答by Rob Grant
This will get the hostname and port of the server, and concatenate the value of the element onto the end, and then go to the resulting URL.
这将获取服务器的主机名和端口,并将元素的值连接到末尾,然后转到生成的 URL。
var triggerNumber = document.getElementById("txtTrigNo").value();
var url = "http://"+window.location.host+"/"+triggerNumber;
window.location = url;