Question

I'm trying to load some Reddit data for a search based on a URL and I keep getting the error Uncaught SyntaxError: Unexpected token : on line 1 of submit.json. I opened submit.json in inspector and checked - the JSON is valid. So, what am I doing wrong? I've tried demos for things like subreddit searching, and this format works fine, it just doesn't seem to work for search.

function loadReddit() {
  var exampleURL = "http://www.reddit.com/submit.json?url=http://www.youtube.com/watch?v=e4dT8FJ2GE0&sort=comments";
  $.ajax({
    url: exampleURL,
    dataType: "jsonp",
    success: function(data) {
      console.log(data);
    }     
  });
}

I've posted a fiddle here with the code, feel free to edit if you feel it is necessary.

Était-ce utile?

La solution

The problem is you're making a JSONP request but the API is giving you a plain JSON response. In JSONP the response JSON is wrapped in a function call, and it's convention that the function's name is given by the callback URL parameter. jQuery generates this parameter for you, but unfortunately Reddit's API is ignoring it.

I had to Google "Reddit API JSONP" to figure it out, but it turns out Reddit expects the parameter to be called jsonp instead of callback. So the solution is use the jsonp option to tell jQuery to put the callback name in the jsonp parameter:

var resourceUrl = "http://www.reddit.com/submit.json",
    params      = { url:  "http://www.youtube.com/watch?v=e4dT8FJ2GE0",
                    sort: "comments" }
;

$.ajax({
  url: resourceUrl,
  data:     params,   // let jQuery deal with URL parameters for you
  dataType: "jsonp",
  jsonp:    "jsonp",  // the name of the URL parameter for jQuery to give the
                      // callback function's name in    
  success: function(data) {
    console.log(data);
  }     
});

This will result in jQuery making a call to a URL like this:

http://www.reddit.com/submit.json
  ? jsonp = jQuery202033503812667913735_1384877326437
  & url   = http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De4dT8FJ2GE0
  & sort  = comments
  & _     = 1384877326438

The jsonp and _ parameters are randomly generated by jQuery. (The _ is meant to force the browser to make a new request instead of the cached result of a previous request. This is documented under, and can be controlled by, the cache option.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top