简体   繁体   中英

Create and go to url with Javascript

I want to be able to produce a URL based on certain properties and then go to the new URL in javascript.

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?

Simply try:

window.location = url;

But before trying to do that, you have to make sure the page at the address "http://" + hostAddress "/" + triggerNumber exists. For example by putting valid triggerNumbers in an array and check if it exists or not. So:

//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:

"http://" + hostAddress "/trigger.php?id=" + triggerNumber;

but you'd better use form s for this.

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.

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.

What you need is:

document.location.href = url;

After you have the URL in the url variable.

To get value of input element have:

var triggerNumber = document.getElementById("txtTrigNo").value;

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.

var triggerNumber = document.getElementById("txtTrigNo").value();
var url = "http://"+window.location.host+"/"+triggerNumber;
window.location = url;

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