更新答案
getJSON
返回一個承諾(只讀延期),這樣你就可以聽。但是由於您需要一些後期處理,您需要鏈接一個then
,它允許您更改已解決的值。
// Now using `then`
function getThumbnail(vUrl){
return $.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl).then(function(data){
return {
thumbnail:data.thumbnail_url,
vurl:vurl
}
});
}
//and in your call will listen for the custom deferred's done
getThumbnail('the_vurl_').then(function(returndata){
//received data!
});
原來的答覆
您可以使用deferred object,並聽取了done()
。
function getThumbnail(vUrl) {
//create our deferred object
var def = $.Deferred();
//get our JSON and listen for done
$.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl)
.done(function(data){
//resolve the deferred, passing it our custom data
def.resolve({
thumbnail:data.thumbnail_url,
vurl:vurl
});
});
//return the deferred for listening
return def;
}
//and in your call will listen for the custom deferred's done
getThumbnail('the_vurl_')
.done(function(returndata){
//received data!
});
您可以返回$.getJSON
的延期以獲取原始數據。但是由於「後處理」到一個對象中,需要延遲的自定義。你也可以傳遞一個回調到getThumbnail()
:
function getThumbnail(vUrl,callback) {
$.getJSON("http://api.embed.ly/1/oembed?key=:key&url="+vurl,function(returndata){
callback(returndata);
});
}
getThumbnail('the_vurl_',function(returndata){
//received data!
})
的
可能重複[?如何返回從AJAX調用的響應(http://stackoverflow.com/questions/14220321/how-to-return-the -response-from-ajax-call) – Bergi