Jquery getJSON Uncaught SyntaxError: Unexpected token : error

后端 未结 4 1383
面向向阳花
面向向阳花 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 16:51

    Related... If you are not returning valid JSON you will see this error, JSONP aside.

    For me I was

    format.json { render :json => ActiveSupport::JSON.encode({:foo => true}) :status => :ok }
    =>
    {
      'foo': true
    }
    

    When I should have been

    format.json { render :json => ActiveSupport::JSON.encode([{:foo => true}]) :status => :ok }
    =>
    [
      {
        'foo': true
      }
    ]
    
    0 讨论(0)
  • 2021-01-03 17:03

    The browser is interpreting the curly brackets as a block. The API needs to return a function call with the JSON data as the argument (using the supplied callback name). It doesn't appear that this API supports JSONP & the callback parameter so you'll need to contact them to ask for this support.

    It should return something like:

    jsonp1279196981233({ ... })
    

    rather than simply:

    { ... }
    

    because the client will be evaluating it as a script. In JavaScript a set of stand alone curly braces will denote a block.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 17:10

    Given that you're passing in a data-handler function to getJSON(), are you sure you want the JSONP callback parameter? Try removing ?jsoncallback=? from the URL:

    .getJSON("http://rubygems.org/api/v1/gems/rails.json", function(data) {
        ...function stuff....
    });
    
    0 讨论(0)
提交回复
热议问题