当我尝试使用 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 行。
添加回答
举报
0/150
提交
取消