Jquery getJSON Uncaught SyntaxError: Unexpected token : error

后端 未结 4 1409
面向向阳花
面向向阳花 2021-01-03 16:27

I am trying to connect to the RubyGems API, but when I try to get the JSON I get an stange error.

Uncaught SyntaxError: Unexpected token :

4条回答
  •  [愿得一人]
    2021-01-03 17:04

    What makes you think that rubygems.org supports JSONP at all? I don't see any mention of JSONP in the documentation and when I do this:

    lynx -dump -source 'http://rubygems.org/api/v1/gems/rails.json?jsoncallback=x'
    

    I get the same plain old JSON as I do from

    lynx -dump -source 'http://rubygems.org/api/v1/gems/rails.json'
    

    The only difference between the two is the downloads and version_downloads change but that's to be expected.

    When you use jsoncallback=? in the query string, jQuery will set up a callback function and assume that the remote URL will send back JavaScript (not JSON!) that will call the specified function. So, if the remote service sends back JSON when you're expecting JavaScript, the browser will end up trying to interpret the JSON as JavaScript and get upset because

    {"dependencies":{"runtime":[{"name":"action ...
    

    is not a valid JavaScript statement. This sounds exactly like the error you're seeing.

    I think you're going to have to proxy the JSON through your own server. You'll need a controller on your server that makes that makes the call to get the JSON and then simply echoes it back to your JavaScript, this will get your around both the lack of JSONP support and your cross domain problem in your client.

提交回复
热议问题