【问题标题】:Get JSON with AJAX in javascript returning NULL instead of JSON object在返回 NULL 而不是 JSON 对象的 javascript 中使用 AJAX 获取 JSON
【发布时间】: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


【解决方案1】:

您还没有定义jsonpcallback,请参考下面的链接这可能会有所帮助

ajax 'GET' call returns jsonp okay but callback produces 'undefined' data

【讨论】:

    【解决方案2】:

    将 'dataType': "jsonp" 改为 'dataType': "json",

    【讨论】:

    • 这将提示我从源“null”访问“file:///{MY_PATH}/products.json”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。
    • @userct 如果您在您的问题中声明,我们早就可以为您解决这个问题。 你所做的是不可能的。从字面上看是不可能的,因为您永远无法使用 ajax 使用标准 Web 浏览器从文件系统中获取 json。
    • 你能做的最好的是将 .json 文件转换为调用方法的 .js 文件,并像其他任何方法一样包含它,或者使用 jsoncallback 参数告诉 jquery 在.js 文件。
    • 是否需要在后端配置 cors 才能工作
    猜你喜欢
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2017-08-17
    • 2014-06-06
    • 2017-12-16
    • 1970-01-01
    • 2016-01-03
    相关资源
    最近更新 更多