简体   繁体   中英

Uncaught SyntaxError: Unexpected token : when returning JSON

I've got some jQuery that is successful in hitting an endpoint, here's my code

$.ajax({
    dataType: "json",
    type: "GET",
    url: "https://url.that-works.com/env/Development/GetDevs/",
    username: "username",
    password: "password",
    data: "callback=?"
})
.done(function (data) {
    alert("success");
})
;

The code returns the following JSON response - which I can see in Chrome Developer Tools:

{
"developments": [
    {
        "name": "h2010 Ph2"
    },
    {
        "name": "The Meadows Ph2"
    },
    {
        "name": "h2010 Ph3"
    },
    {
        "name": "h2010 Ph4"
    },
    {
        "name": "The Meadows Ph3"
    }
  ]
}

I've checked that this is valid JSON being returned, but I keep getting an error message: Uncaught SyntaxError: Unexpected token :

I'm not sure what exactly I'm doing wrong here or why I'm getting this message, any guidance would be really appreciated.

bengrah.

In jQuery docs you can find the following:

'Cross-domain json requests are converted to jsonp unless the request includes jsonp: false in its request options.'

So probably you are making a cross domain call and it is converted to jsonp because you have specified dataType: 'json' .

When in JSONP mode, jQuery looks for such kind of response:

jQuery18406445654265099913_1319844792316({
"developments": [
    {
        "name": "h2010 Ph2"
    },
    {
        "name": "The Meadows Ph2"
    },
    {
        "name": "h2010 Ph3"
    },
    {
        "name": "h2010 Ph4"
    },
    {
        "name": "The Meadows Ph3"
    }
  ]
}) 

but not a JSON string, so you are getting an error during the convertion. JSONP expects a javascript, not a string. If you take a look at the jQuery code you can make it more clear for you, but that's in general.

Eventually figured out the answer.

In our case, we were using a middleware appliance that generates the above URL/orchestration the script hits to get the JSON and so on. What we were trying to do was use a JSONP request to get at this info, but the orchestration returns JSON that wasn't wrapped in a function , which is where our problem lies.

Instead, we changed it to a standard JSON get request, which then caused the Access-Control-Allow-Origins error (good link here ). At this point, we added the Access-Control-Allow-Origins setting to the orchestration/server side - then we were able to get the JSON back in a usable format successfully.

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