javascript - 使用 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 代码可以正常工作。
非常感谢。
解决方案
推荐阅读
- html - 检测 iframe 内的重定向
- wordpress - 自定义注册表
- python - Python 创建包以供本地使用
- python - 获取任何 QKeyEvent 键值的可打印名称
- amazon - 如何在 codeigniter 中包含 amazon mws MarketplaceWebServiceProducts 客户端库
- java - jOOQ join 选择对象
- python - Python @property setter 未从实例调用中设置
- qt - 如何使自定义 QWidget 部分透明?
- php - 如何使 Wordpress 帖子输出按帖子标题中指定的日期排序?以及如何显示标题中带有日期的帖子> =今天的日期?
- android - 错误:未知元素
升级到android 3.1后发现