使用成功 / jsonpCallback 与 ajax 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7167488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 11:03:19  来源:igfitidea点击:

Use of success / jsonpCallback with ajax request

ajaxcallbackjsonpodata

提问by Andy

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

我正在使用他们的 OData API 为 Netflix 开发应用程序。我关注了Stephen Walther关于如何查询 OData API的博客条目。在其中,他使用了以下代码:

$.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:

在我的应用程序中,我需要使用 OData 的分页链接来检索完整列表。我的代码如下:

// 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: callbackline, the application works fine. My question is: Is there a problem with leaving the successline of code from the ajax call? Or why would it be necessary to include both the jsonpCallbackand successlines? I'm mainly asking this out of curiosity, because the application seems to work fine without both callback lines.

但是,当它运行时,我不断收到parserError. 看来回调函数被调用了两次。如果我删除该success: callback行,应用程序工作正常。我的问题是:success从 ajax 调用中离开代码行是否有问题?或者为什么有必要同时包含jsonpCallbacksuccess行?我主要是出于好奇而问这个问题,因为应用程序在没有两个回调行的情况下似乎可以正常工作。

采纳答案by David Hoerster

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

根据您的代码尝试执行的操作,我不确定您为什么在通话中同时指定jsonpCallback和。我建议您只指定以便处理您的数据和处理您的分页。让 jQuery 定义 jsonp 回调的名称。success$.ajaxsuccess

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 jsonpCallbackif you wanted to do some caching or some other pre-processing of the data before it gets handled by your successhandler. I'm not sure why you'd specify the same function as both your jsonpCallbackand successhandlers in this case. (I briefly looked through Stephen's article that you linked to, and I'm not why he does this.)

本质上,jsonp 回调所做的是从 WCF 数据服务接收有效负载,然后将其交给成功处理程序。jsonpCallback如果您想在处理success程序处理数据之前对数据进行一些缓存或其他一些预处理,看起来您可以使用它。在这种情况下,我不确定为什么要为您的处理程序jsonpCallbacksuccess处理程序指定相同的功能。(我简要浏览了您链接到的斯蒂芬的文章,我不知道他为什么这样做。)

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 JSONPSupportBehaviorAttributein order to enable JSONP in my WCF Data Service (not sure if that's what you're using or not).

下面是我在演示和谈话中使用的 WCF 数据服务的示例 jsonp 调用(并且已经使用了一段时间)。我使用 是JSONPSupportBehaviorAttribute为了在我的 WCF 数据服务中启用 JSONP(不确定这是否是您正在使用的)。

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

但是在我的示例代码中,我没有指定jsonpCallback名称;我只是指定了jsonp查询字符串参数(必须是$callback而不是默认值callback),但我让 jQuery 命名了 jsonp 回调函数。

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

我的success处理程序被调用一次,一切正常。所以我的建议是忘记jsonpCallback,保持你的success处理程序就位,我认为事情应该开始变得更好。

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>");
        });
    }
});

回答by Joe

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

不要定义callback,因为 jQuery 会为您创建该函数。这是一个例子,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.

callback=?基本上要求 jQuery 处理所有 JSONP 返回。