Pregunta

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

¿Cómo puedo devolver el valor al valor de la persona que llama? Gracias.

EDITAR: he intentado esto:

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

Pero tampoco funciona. Devuelve nulo.

¿Fue útil?

Solución

Supongo que desea utilizar un evento sincrónico para que su función String.prototype.getLanguage () solo devuelva el JSON. Lamentablemente, no puede hacerlo con jQuery desde una API remota.

Hasta donde yo sé, jQuery no es compatible con XMLHttpRequest síncrono objetos , e incluso si lo hiciera, necesitaría tener un proxy en su servidor para realizar la solicitud de sincronización mientras evita las restricciones de política del mismo origen .

Sin embargo, puede hacer lo que quiera con el soporte de jQuery para JSONP. Si solo escribimos String.prototype.getLanguage () para admitir una devolución de llamada:

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

Entonces podemos usar la función 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);
});

Otros consejos

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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top