Domanda

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

Come posso restituire il valore al valore del chiamante? Grazie.

EDIT: ho provato questo:

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

Ma non funziona neanche. Restituisce null.

È stato utile?

Soluzione

Suppongo che tu voglia utilizzare un evento sincrono in modo che la tua funzione String.prototype.getLanguage () restituisca semplicemente JSON. Sfortunatamente non puoi farlo con jQuery da un'API remota.

Per quanto ne so jQuery non supporta XMLHttpRequest sincrono oggetti e, anche se fosse così, dovresti avere un proxy sul tuo server per effettuare la richiesta di sincronizzazione evitando le restrizioni di politica della stessa origine .

Tuttavia, puoi fare ciò che desideri utilizzando il supporto di jQuery per JSONP. Se scriviamo semplicemente String.prototype.getLanguage () per supportare un 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);
    });
}

Quindi possiamo usare la funzione come tale:

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

Altri suggerimenti

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);
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top