Modifying JSONP results before success callback

▼魔方 西西 提交于 2019-12-10 22:56:43

问题


I'd like to load some JSON data from an external service. However, it provides

{ foo: ..., bar: ..., useful: {...} }

and what I really care about is in the "useful" part. I need to pass just that part to the success callback.

I'm trying to use Deferred to load from multiple data sources at once -- something like this. I'd like to retrieve the data, "massage" the result, and have just the "useful" part in the example above actually passed to the then callback. My understanding is that when you pass a Deferred to when(), the data goes directly to the callback passed to then(), so I need to hook into the process before it gets there.

I tried dataFilter but for JSONP that's not possible. Is there any other way to intercept these results? I can add some checks to my then() callback to handle cached data differently from the "fresh" results, but that sort of loses the magic of Deferred in the first place.

To clarify, this doesn't work:

$.when($.ajax({
  url: "host/service",
  dataType: "jsonp",
  dataFilter: function(data, type){
    return data.useful; // throws, data === undefined
  }
})).then(function(usefulStuff){ ... });

回答1:


You can call .pipe() to process the data and create a new Deferred:

$.getJSON(...).pipe(function(results) {
    return ...;
})


来源:https://stackoverflow.com/questions/13649399/modifying-jsonp-results-before-success-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!