问题描述
我想从外部服务加载一些JSON数据。但是,它提供了
I'd like to load some JSON data from an external service. However, it provides
{ foo: ..., bar: ..., useful: {...} }
我真正关心的是有用部分。我需要将该部分传递给 success
回调。
and what I really care about is in the "useful" part. I need to pass just that part to the success
callback.
我正在尝试使用 Deferred
一次从多个数据源加载 - 类似于。我想检索数据,按下结果,并在上面的例子中只有有用部分实际传递给然后
回调。我的理解是当你将 Deferred
传递给时()
,数据直接传递给传递给 then(),所以我需要在它到达之前挂钩进程。
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.
我试过 dataFilter
但对于。有没有其他方法来拦截这些结果?我可以在我的 then()
回调中添加一些检查来处理缓存数据,与新鲜结果不同,但是那种失去了的魔力首先推迟
。
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){ ... });
推荐答案
您可以拨打 .pipe ()
处理数据并创建一个新的Deferred:
You can call .pipe()
to process the data and create a new Deferred:
$.getJSON(...).pipe(function(results) {
return ...;
})
这篇关于在成功回调之前修改JSONP结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!