简体   繁体   中英

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. Now jQuery is loading correctly and in my app I have the following code:

$('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:

[{
    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 . 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. 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. If you were using the fail callback of the returned promise, I expect you'd be seeing that get called.

In JSON, keys must be in double quotes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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