简体   繁体   English

jQuery $ .getJSON不返回任何数据,但状态为200 OK

[英]jQuery $.getJSON not returning any data but getting status of 200 OK

I am using jQuery 1.11.1 hosted by Google CDN and I am running a local simple server using python -m SimpleHTTPServer on my machine. 我正在使用Google CDN托管的jQuery 1.11.1,并且正在我的计算机上使用python -m SimpleHTTPServer运行本地简单服务器。 Now jQuery is loading correctly and in my app I have the following code: 现在jQuery正在正确加载,在我的应用程序中,我有以下代码:

$('document').ready(function () {

    // let's get the products
    $.getJSON( 'scripts/products.js', function ( data ) {
        console.log('got here');
        console.log(data);
    });

})

at this stage I just want to be sure that I am receiving my JSON which is in the file scripts/products.js and contains the following code only: 在此阶段,我只想确保我接收到我的JSON,它位于scripts / products.js文件中,并且仅包含以下代码:

[{
    product: "Product 1",
    size: "S",
    price: 10.99
},
{
    product: "Product 2",
    size: "M",
    price: 12.99
},
{
    product: "Product 3",
    size: "L",
    price: 13.99
}]

I am getting no error from the console and the dev tools are showing that the products file is being loaded! 我从控制台没有收到任何错误,并且开发工具正在显示正在加载产品文件! I am seeing a status of 200 OK . 我看到状态为200 OK So why aren't the console logs in my callback being called? 那么,为什么控制台日志中没有调用我的回调? If I try to loop through the data nothing happens? 如果我尝试遍历数据,没有任何反应?

What you've quoted isn't valid JSON. 您引用的不是有效的JSON。 If jQuery is deferring to the browser's built-in JSON.parse , and the browser's JSON.parse is strict (as most are, I believe), although you're retrieving the text of the products.js file, the parsing fails. 如果jQuery遵循浏览器的内置JSON.parse ,并且浏览器的JSON.parse是严格的(我相信大多数情况下都如此),尽管您正在检索products.js文件的文本,但解析失败。 If you were using the fail callback of the returned promise, I expect you'd be seeing that get called. 如果您使用的是返回的诺言的fail回调 ,那么我希望您会看到被调用。

In JSON, keys must be in double quotes: 在JSON中,键必须用双引号引起来:

[{
    "product": "Product 1",
    "size": "S",
    "price": 10.99
},
{
    "product": "Product 2",
    "size": "M",
    "price": 12.99
},
{
    "product": "Product 3",
    "size": "L",
    "price": 13.99
}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM