javascript - Javascript redirect (window.location.href) doesn't work in an Asp.NET Core project when called from an EventListener function
问题描述
So upon clicking button the script sends a POST request, which is correctly processed and the following response is sent
redirectUrl = Request.Host + "/" + page.PageURL;
return Json(new { url = redirectUrl });
The above described process is initiated by the following code
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
handleRequestSent(request);
The part below properly parses the return Json and gives the proper url (localhost:5001/pagename)
function handleRequestSent(request) {
request.addEventListener("readystatechange", function () {
console.log(this);
if (this.readyState === 4) {
var responseData = JSON.parse(this.responseText);
console.log(responseData.url);
redirectToPage(responseData.url);
};
});
}
This is the part that doesn't work. But it only seems not to work when called from the above code. When I called this method directly it redirected me to the indicated address.
function redirectToPage(redirectUrl) {
window.location.href = redirectUrl;
}
I have also tried various other forms that do the same thing as window.location.href but none of them worked. What's going on here?
解决方案
You forget to add request scheme to the redirectUrl:
redirectUrl = Request.Scheme + "://" + Request.Host + "/" + page.PageURL;
推荐阅读
- javascript - 使用谷歌登录时出错-vue“未定义gapi”
- c++ - 尝试实现我自己的 << 和 >> 流操作符来操作我的 Grid 对象
- java - 在没有 NodeJS 的情况下使用 EJS
- java - 如何访问 Tomcat 中的环境变量?
- etl - 通过 ODI (Oracle Data Integrator) 调用选择脚本
- python - 如何不覆盖数据框中的 csv 文件?
- selenium - 在 Selenium Grid 上运行时,Selenium IDE 测试失败
- java - findBeans Spring 的问题
- c - *.i 文件中的 # 数字代表什么
- javascript - 首先加载页眉和页脚