mko
mko

Reputation: 22104

Why the callback of getJSON function doesn't executed?

I found that jquery has a solution for CORS

here's the code in the js file:

   $.getJSON('http://localhost:8001/location?callback=?', function(data){
        console.log(data[]);
        console.log("anything");

    });

the server json API: for the http://localhost:8001/location?callback=? request, return

({url:'bar'})

The problem is the console.log() never executed, I put break point in there, but the browser doesn't stop there.

PS the cross domine request is successful, because I can see the responds json file is in the resources list in the web inspector

Any idea?

Upvotes: 0

Views: 816

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075039

Well, the code as presented in the question won't run at all (it won't even make the request), because it has a syntax error:

console.log(data[]);
// Here --------^^

But I assume from your saying you've seen the response that you must have tested without that error at some point.

Your server response is incorrect. You've said

the server json API: for the http://localhost:8001/location?callback=? request, return

({url:'bar'})

...but that's not a valid JSONP response (it's also not a valid JSON response, in three different ways). To form the correct JSONP response, you have to respond with a JavaScript function call using the function name you receive in the callback query string parameter. So for instance, if callback is __jquery456481345, then the response should be:

__jquery456481345({"url":"bar"})

About JSON: I've said above that ({url:'bar'}) is not a valid JSON response in three different ways. Again, in your example you're using JSONP (which is different), but just for completeness, here are the problems with that as JSON:

  1. A JSON document cannot start with (, it must start with { or [.

  2. In JSON, property names (keys) must be in double quotes, e.g. "url": ..., not url: ....

  3. In JSON, strings must be in double quotes, single quotes are not valid like they are in JavaScript. So "bar", not 'bar'.

Upvotes: 3

Related Questions