【问题标题】:window.location.replace unexpected behaviourwindow.location.replace 意外行为
【发布时间】:2021-12-18 21:37:33
【问题描述】:

我有一个按钮,当单击该按钮时,它会向我的 API 发起 POST 请求。 然后我想从 API 调用中获取响应 URL 并重定向到它。

这就是我的 JS 的样子:

function submitPassowrd(url) {
let xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
let u = xhr.responseText
if (xhr.status === 200) {
    window.location.replace(u);
    return false
}
return false
}

问题在于,它不是从 API 响应重定向到 URL,而是将其连接到基本 URL。所以如果 URL 是http://example.com,它会像这样添加它:http://127.0.0.1:8081/http://example.com

也就是说,当我使用硬编码的 URL 时,它可以正常工作并将我正确重定向到 window.location.replace 中提供的网站。例如:

function submitPassowrd(url) {
let password = document.getElementById('password').value;
let xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify();
let u = xhr.responseText
if (xhr.status === 200) {
    window.location.replace('http://example.com'); // <<<<<<< hard-coded URL
    return false
}
return false
}

另外,我尝试使用 window.location.href 导致完全相同的行为。

什么可以解释这种行为?

【问题讨论】:

    标签: javascript html api


    【解决方案1】:

    对于这个用例恕我直言,您应该使用window.location.href 或简单地使用window.location 而不是window.location.replace

    话虽如此,.replace 行为的可能解释是 url 被编码,因此不被视为 url(而只是字符串),因此被连接到当前页面 url。可以console.logu的输出,看看返回的字符串是否被编码?

    【讨论】:

    • 谢谢。我忘了提,但我也尝试过使用 window.location.href。相同的行为。
    • 我更新了答案,请仅尝试 window.location 和 console.log u的输出
    • u 的输出只是 URL 本身(作为字符串)
    • 仅尝试 window.location
    • window.location 也是如此
    猜你喜欢
    • 2017-03-10
    • 2019-05-01
    • 2011-07-15
    • 2011-04-27
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多