Alo*_*kin 5 javascript 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;
});
};
Run Code Online (Sandbox Code Playgroud)
如何将值返回给调用者值?谢谢.
编辑:我试过这个:
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;
};
Run Code Online (Sandbox Code Playgroud)
但它也没有用.它返回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);
});
}
Run Code Online (Sandbox Code Playgroud)
然后我们可以使用这样的函数:
'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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14527 次 |
| 最近记录: |