Pergunta

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

Como posso devolver o valor para o valor de chamadas? Obrigado.

EDIT: Eu tentei isso:

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

Mas não é funcionando. Ele retorna null.

Foi útil?

Solução

Eu estou supondo que você quer usar um evento síncrono de modo que sua função String.prototype.getLanguage () irá retornar apenas o JSON. Infelizmente você não pode fazer isso com jQuery de uma API remoto.

Tanto quanto eu sei jQuery não apoiar síncrona XMLHttpRequest objetos , e mesmo que o fizesse, você precisa ter um proxy no seu servidor para fazer a solicitação de sincronização, evitando as restrições do mesma origem política .

Você pode, no entanto, fazer o que quiser com o apoio da jQuery para JSONP. Se nós apenas escrever String.prototype.getLanguage () para suportar uma chamada de retorno:

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

Então, podemos usar a função como tal:

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

Outras dicas

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);
};
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top