我有这个 html 文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML Program</title>
</head>
<body>
<h1>Hello World!</h1>
<iframe id='MyFrame' style="width: 80vw; height: 80vh"> </iframe>
<script>
const myFile = "settings.txt";
document.getElementById('MyFrame').setAttribute("src", myFile);
</script>
</body>
</html>
和settings.txt:
desmos.com/calculator
我希望从 settings.txt 文件中获取任意 URL 并在 iframe 中显示该网页,但 iframe(正确地)将 url 解释为原始文本。我如何让它显示网页?
欢迎任何反馈!
你必须使用 XMLHttpRequest 从文件中获取 URL 并显示目的,将你的脚本标签修改为:
<script>
const myFile = "settings.txt";
const xhr = new XMLHttpRequest();
xhr.open('GET', myFile, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const url = xhr.responseText.trim();
document.getElementById('MyFrame').setAttribute("src", url);
}
};
xhr.send();
</script>