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;
};
但它也不起作用。它返回空值。
最佳答案
我假设您想使用同步事件,这样您的 String.prototype.getLanguage() 函数将只返回 JSON。不幸的是,您不能通过远程 API 使用 jQuery 来做到这一点。
据我所知jQuery不支持synchronous XMLHttpRequest objects ,即使这样做了,您也需要在您的服务器上有一个代理来发出同步请求,同时避免 same-origin policy 的限制。 .
但是,您可以使用 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);
});
关于javascript - jQuery getJSON - 将值返回给调用者函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1229307/