【发布时间】: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