【发布时间】:2019-12-25 01:12:20
【问题描述】:
当我尝试使用 ajax 检索 JSON 时,我首先遇到了 CORS 问题,我通过将 crossDomain 启用为 true 并将 dataType 添加为 jsonp(注意“p”)来解决这个问题。 运行脚本时,它返回 null 而不是它应该从 JSON 中获取的数据
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var json = (function() {
var json = [];
$.ajax({
'async': false,
'global': false,
'crossDomain': true,
'method': "get",
'url': "products.json",
'dataType': "jsonp",
'success': function (data) {
json = data;
}
});
return json;
})();
console.log(json);
</script>
</body>
</html>
JSON
{
"items": [{
"title": "Express"
}, {
"title": "Unexpress"
}]
}
我期望一个 json,但它在控制台中返回 null 和一条消息:“Uncaught SyntaxError: Unexpected token :”在 JSON 的第 2 行。
【问题讨论】:
-
你从哪里得到 JSON?
-
硬盘。它将从 c:\products.json 获取 json
-
忘记最后一条评论,我是从项目根目录获取的
-
好吧,尝试打开 Inspector (ctrl + shift + i) 并转到网络选项卡,然后刷新页面,看看你在那里得到了什么,应该有一个请求
-
是的,我确实收到了“已完成”状态
标签: javascript ajax