Skip to content Skip to sidebar Skip to footer

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=?', fu

Solution 1:

I'm assuming you want to use a synchronous event so that your String.prototype.getLanguage() function will just return the JSON. Unfortunately you can't do that with jQuery from a remote API.

As far as I know jQuery does not support synchronous XMLHttpRequest objects, and even if it did, you'd need to have a proxy on your server to make the sync request while avoiding the restrictions of the same-origin policy.

You can, however, do what you want using jQuery's support for JSONP. If we just write String.prototype.getLanguage() to support a callback:

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

Then we can use the function as such:

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

Solution 2:

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

Post a Comment for "Jquery Getjson - Return Value To The Caller Function"