Question

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

Comment puis-je retourner la valeur à la valeur de l'appelant? Merci.

EDIT: j'ai essayé ceci:

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

Mais ça ne marche pas non plus. Il retourne null.

Était-ce utile?

La solution

Je suppose que vous souhaitez utiliser un événement synchrone pour que votre fonction String.prototype.getLanguage () renvoie simplement le code JSON. Malheureusement, vous ne pouvez pas faire cela avec jQuery à partir d'une API distante.

Pour autant que je sache, jQuery ne prend pas en charge les synchrone XMLHttpRequest. objets , et même si c'était le cas, vous auriez besoin d'un proxy sur votre serveur pour effectuer la demande de synchronisation tout en évitant les restrictions de règles de même origine .

Vous pouvez toutefois faire ce que vous voulez en utilisant le support de JQuery pour JSONP. Si nous écrivons simplement String.prototype.getLanguage () pour prendre en charge un rappel:

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

Ensuite, nous pouvons utiliser la fonction en tant que telle:

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

Autres conseils

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);
};
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top