[英]jQuery getJSON - Return value to the caller function
String.prototype.getLanguage = function() {
$.getJSON('http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=' + this + '&callback=?',
function(json) {
return json.responseData.language;
});
};
如何將值返回給調用者值? 謝謝。
編輯:我試過這個:
String.prototype.getLanguage = function() {
var returnValue = null;
$.getJSON('http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=' + this + '&callback=?',
function(json) {
returnValue = json.responseData.language;
});
return returnValue;
};
但它也沒有用。 它返回null。
我假設您要使用同步事件,以便您的String.prototype.getLanguage()函數將只返回JSON。 不幸的是,你不能用遠程API中的jQuery做到這一點。
據我所知,jQuery不支持同步XMLHttpRequest對象 ,即使它確實存在,您也需要在服務器上設置代理來發出同步請求,同時避免同源策略的限制。
但是,您可以使用jQuery對JSONP的支持來執行您想要的操作。 如果我們只編寫String.prototype.getLanguage()來支持回調:
String.prototype.getLanguage = function( callback ) {
var thisObj = this;
var url = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=' + this + '&callback=?';
$.getJSON( url,function(json) {
callback.call(thisObj,json.responseData.language);
});
}
然后我們可以使用這樣的函數:
'this is my string'.getLanguage( function( language ) {
//Do what you want with the result here, but keep in mind that it is async!
alert(this);
alert(language);
});
var test = function(fun)
{
String.prototype.getLanguage = function() {
.getJSON('http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=' + this + '&callback=?',
function(json) {
fun.call(json.responseData.language);
});
};
};
test(retCall);
var retCall = function(xjson){
alert(xjson);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.