我有一个按钮,可以在单击时打开模式。该模式显示来自服务器上不同文件 url 的页面。但是,当我将它从 localhost 移动到 stage 时,该文件的 url 发生了变化,模态无法再读取该文件。
所以我一直在想办法让它自动知道该文件的更新 url,而不是我输入实际 url。我试过使用 window.location.href 但这会打开按钮位于模态中的页面,而不是在模态中打开不同的文件。
<script>
btn.onclick = function() {
modal.style.display = "block";
let url = "http://localhost:1111/hello";
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4){
if (request.status == 200){
document.getElementById("modal_text").innerHTML = request.responseText;
} else {
//handle error
}
}
};
request.open('GET', url);
request.send();
</script>
最佳答案
您可以使用根相对 url:
let url = "/hello";
浏览器将知道使用来自当前位置
的相同协议(protocol)、主机和端口
关于javascript - 如何在单击按钮时以模式读取页面的当前 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137379/