Use of success / jsonpCallback with ajax request

2019-01-18 14:43发布

I'm developing an application for Netflix using their OData API. I've followed Stephen Walther's blog entry on how to query the OData API. In it, he uses the following code:

$.ajax({
   dataType: "jsonp",
   url: query,
   jsonpCallback: "callback",
   success: callback
}); 

In my application, I need to use the OData's paging links, to retrieve the full listings. My code is as follows:

// create url and handle ajax call to Netflix
  function getTitles() {
    query = "http://odata.netflix.com/v2/Catalog" // netflix odata base url
    + "/Genres('Television')" // select Genre
    + "/Titles" // top-level resource
    + "?$select=NetflixApiId,Name,BoxArt,Synopsis,ReleaseYear,AverageRating,Series" // choose fields 
    + "&$orderby=Name" // Sort results by name
    + "&$filter=Instant/Available eq true"  // filter by instant view
    + " and Type eq 'Season'" // select only seasons
    + "&$expand=Series" // include series data
    + "&$callback=callback" // specify name of callback function
    + "&$format=json"; // json request
    $.ajax({
      dataType: "jsonp",
      url: query,
      jsonpCallback: "callback",
      success: callback,
      error: function(XHR, textStatus, errorThrown){
        alert(textStatus + ":" + errorThrown);
      } 
    });
  }

// create seasons array and and repeat ajax call until all results are returned 
  function callback(result) {
    seasons = seasons.concat(result["d"]["results"]);
    if (typeof result["d"]["__next"] != 'undefined') {
      var urlJSONP = result["d"]["__next"] + "&$callback=callback&$format=json";
      $.ajax({
        dataType: "jsonp",
        url: urlJSONP,
        jsonpCallback: "callback",
        success: callback,
        error: function(XHR, textStatus, errorThrown){
          alert(textStatus + ":" + errorThrown);
        } 
      });
    } else {
      processResults();
    }
  }

However, when this runs I keep getting a parserError. It appears that the callback function is being called twice. If I remove the success: callback line, the application works fine. My question is: Is there a problem with leaving the success line of code from the ajax call? Or why would it be necessary to include both the jsonpCallback and success lines? I'm mainly asking this out of curiosity, because the application seems to work fine without both callback lines.

2条回答
太酷不给撩
2楼-- · 2019-01-18 15:10

Don't define callback, because jQuery creates that function for you. Here's an example, jsFiddle:

function getTitles() {
    query = "http://odata.netflix.com/v2/Catalog" // netflix odata base url
    + "/Genres('Television')" // select Genre
    + "/Titles" // top-level resource
    + "?$select=NetflixApiId,Name,BoxArt,Synopsis,ReleaseYear,AverageRating,Series" // choose fields 
    + "&$orderby=Name" // Sort results by name
    + "&$filter=Instant/Available eq true"  // filter by instant view
    + " and Type eq 'Season'" // select only seasons
    + "&$expand=Series" // include series data
    + "&$callback=?" // specify name of callback function
    + "&$format=json"; // json request
    $.ajax({
      dataType: "jsonp",
      url: query,
      success: callback,
      error: function(XHR, textStatus, errorThrown){
        alert(textStatus + ":" + errorThrown);
      } 
    });
  }

callback=? basically asks jQuery to handle all the JSONP returns.

查看更多
Deceive 欺骗
3楼-- · 2019-01-18 15:23

Based on what your code is trying to do, I'm not sure why you're specifying both jsonpCallback and success in your $.ajax call. I would suggest you just specify success in order to process your data and handle your paging. Let jQuery define the name of your jsonp callback.

Essentially what the jsonp callback is doing is receiving the payload from your WCF Data Service and then handing it to your success handler. It looks like you could use jsonpCallback if you wanted to do some caching or some other pre-processing of the data before it gets handled by your success handler. I'm not sure why you'd specify the same function as both your jsonpCallback and success handlers in this case. (I briefly looked through Stephen's article that you linked to, and I'm not why he does this.)

Below is a sample jsonp call to a WCF Data Service that I use in demos and talks (and have been using for a little while). I use the JSONPSupportBehaviorAttribute in order to enable JSONP in my WCF Data Service (not sure if that's what you're using or not).

But in my sample code, I don't specify a jsonpCallback name; I just specify the jsonp querystring parameter (has to be $callback instead of the default callback), but I let jQuery name the jsonp callback function.

My success handler is called once and everything works fine. So my suggestion is to forget about jsonpCallback, keep your success handler in place, and I think things should start to work better.

I hope this helps. Let me know if you have follow-on questions. Good luck!

$.ajax({
    url: 'http://server:25812/Services/AgileWays.Baseball.Service.svc/Teams?$format=json&$filter=yearID eq 1882',
    type: 'GET',
    dataType: 'jsonp',
    cache: false,
    jsonp: '$callback',
    error: function (x, t, r) { alert(x.response.message); },
    success: function (data) {
        $.each(data.d.results, function (i, val) {
            $("#results").append("<div>" + val.name + "</div>");
        });
    }
});
查看更多
登录 后发表回答