Reputation: 11
The script I'm writing is for an HTML page that is meant to make an ajax request, the response is an external link. Then the browser is supposed to redirect to this external URL (ex. from localhost:3000 to www.stackoverflow.com). However, the URL is appended instead (localhost:3000/"www.stackoverflow.com"). How can I redirect to a new page in pure javascript?
I've already attempted the following: window.location.href =, location.href =, window.location.replace(), window.location.assign(). All of these resulted in appending the URL instead.
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
window.location.href = http.response
}
}
http.open("GET", "/1", true);
http.send();
Upvotes: 1
Views: 1764
Reputation: 16777
Assuming your response
variable looks like this:
'www.stackoverflow.com'
You should prepend http://
(or https://
) to it before assigning to location.href
to ensure that the browser interprets it as an absolute (as opposed to relative) URL.
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
window.location.href = 'http://' + http.response
}
}
http.open("GET", "/1", true);
http.send();
If you are unsure whether your response
contains the URL scheme, you can make your code a little more flexible with a regular expression check:
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
var url = http.response
window.location.href = (/^https?:\/\//.test(url) ? '' : 'http://') + url
}
}
http.open("GET", "/1", true);
http.send();
Upvotes: 0
Reputation: 6610
Just change it to
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
window.location.href = 'http://' + http.response.replaceAll("^\"|\"$", "");
}
}
http.open("GET", "/1", true);
but if any url send by the server already has 'http://' in it, you have to treat this before assigning the url http.send();
The .replaceAll("^\"|\"$", "")
is for removing the double quotes your server seems to be sending also.
Upvotes: 0