javascript - 为什么 $.getJSON 返回带有有效 JSON 文件的 ParseError?
问题描述
我正在尝试从本地文件中获取 JSON 数据:
$.getJSON(file, function(json_data) {
console.log(json_data);
}).fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); });
但是,尽管根据https://jsonlint.com/我的文件是一个有效的 JSON 文件,我总是得到 ParseError。
我试图通过$.get(...)
请求获取内容,但是,如果这样做,我会得到<empty string>
内容。
谁能帮助我?
解决方案
var getProductDataFromJson = new Promise(
function (resolve) {
$.getJSON("https://raw.githubusercontent.com/bmehler/product/main/product.json", function(data) {
resolve(data);
});
}
);
getProductDataFromJson
.then(function (data) {
console.log('data', data);
})
.catch(function (error) {
console.log(error.message);
});
这段代码应该可以工作。只需复制我的 json 文件并输入您的数据即可。