AJAX call and clean JSON but Syntax Error: missing ; before statement

JZweige picture JZweige · Oct 18, 2013 · Viewed 56k times · Source

I am making a cross domain JSONP call using this code:

jQuery.ajax({
        async: true,
        url: 'http://mnews.hostoi.com/test.json',
        dataType: 'jsonp',
        method: "GET",
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            if (data.Error || data.Response) {
                exists = 0;
            }
        }
    });

When debugging in Firebug, I get the following error:

enter image description here

SyntaxError: missing ; before statement

However, when I pass my json object (available through the link in the JQ code) through a tool like jsonlint.com, it says it is valid JSON. And I don't find any anomalies either. How could it be returning a syntax error? Is it some JSONP detail I am not getting or what?

JSON Sample

{"news":[ {
  "sentences": [
    "Neuroscientists have discovered abnormal neural activity...", 
    "The researchers found that these mice showed many symptoms...", 
    "\"Therefore,\" the study authors say, \"our findings provide a novel.."
  ], 
  "summaryId": "ZJEmY5", 
  "title": "Abnormal neural activity linked to schizophrenia"
}]}

Thanks in advance.

Answer

Quentin picture Quentin · Oct 18, 2013

JSONP is not JSON. A JSONP response would consist of a JavaScript script containing only a function call (to a pre-defined function) with one argument (which is a JavaScript object literal conforming to JSON syntax).

The response you are getting is JSON, not JSONP so your efforts to handle it as JSONP fail.

Change dataType: 'jsonp' to dataType: 'json' (or remove the line entirely, the server issues the correct content-type so you don't need to override it).

Since your script is running on a different origin to the JSON then you will also need to take steps (most, but not all, of which require that you control the host serving the JSON) to work around the same origin policy.