在javascript中使用AJAX获取JSON返回NULL而不是JSON对象

当我尝试使用 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 行。


长风秋雁
浏览 305回答 2
2回答

子衿沉夜

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

呼唤远方

你还没有定义jsonpcallback,参考下面的链接这可能有帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript