jQuery getJSON – 返回调用函数的值

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); };