首页 > 解决方案 > 随机 HTML 页面脚本在边缘而不是 chrome 上工作

问题描述

我有一个随机调用与一些 JS 内联的 HTML 页面的脚本。它在 Edge 上运行良好,但在 chrome 上却不行。如何让它在 Chrome 上运行?

试图换个头,但我不知道出了什么问题。

function loadExternalHTMLPage() {
  var xmlhttp;
  var pagesToDisplay = ['1.html', '2.html'];
  
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById("contentArea").innerHTML = xmlhttp.responseText;
    }
  }
  
  var randomnumber = Math.floor(Math.random() * pagesToDisplay.length);
  xmlhttp.open("GET", pagesToDisplay[randomnumber], true);
  xmlhttp.send();
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Random principle</title>
</head>
<script language="javascript" type="text/javascript" src="javascript.js"></script>

<body onload="loadExternalHTMLPage()">
  <div id="contentArea">
  </div>
</body>

</html>

标签: javascript

解决方案


当您使用 XMLHttpRequest 加载文件时,您需要使用一些服务器来托管文件。如果您使用 VS 代码作为代码编辑器,您可以安装 Live 服务器扩展并使用 Live 服务器打开文件。

https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer


推荐阅读