首页 > 解决方案 > 使用 typeScript 获取本地 JSON 文件。我在静态页面中遇到跨源错误

问题描述

我正在使用 typeScript 来获取本地 JSON 文件。我在静态页面中遇到跨域错误。这是我的代码:

window.onload = function() {
//   // all of your code goes in here
//   // it runs after the DOM is built
function loadJSON(path, success, error) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        if (success) success(JSON.parse(xhr.responseText));
      } else {
        if (error) error(xhr);
      }
    }
  };
  xhr.open("GET", path, true);
  xhr.send();
}

loadJSON(
  "../dataBase/electrical.json",
  function(data) {
    console.log(data);

    function getSgItem() {
      let sg = "";

      data.forEach(function(item) {
        sg += `
                <div class="data">
                    <div class="image">
                    <img src="../images/electrical/scherer01.png" alt="" />
                    </div>
                    <div class="dataContent">
                    <h2>${item.sgice}</h2>
                    <h1>${item.name}</h1>
                    <div class="button">
                        <div class="buttonInfo">
                        <h3>SHIPS#</h3>
                        <h3>${item.ships}</h3>
                        </div>
                        <button>
                        <a href=${item.link}>CLICK HERE</a>
                        </button>
                    </div>
                    </div>
                </div>
            `;
      });
      document.getElementById("sg").innerHTML = sg;
    }

    getSgItem();
  },
  function(xhr) {
    console.error(xhr);
  }
);
}

我需要将它作为公司内部服务器的静态页面运行。有没有办法来解决这个问题?

当我右键单击并使用实时服务器打开时,使用 vs 代码可以正常工作。

非常感谢。

标签: javascriptjsontypescript

解决方案


推荐阅读