Here is a class I made which uses YQL to do Google Translate.
var Translator = {
source: 'ro', // default
target: 'en', // default
url: 'http://query.yahooapis.com/v1/public/yql?q=select * from google.translate where q="',
urlRemaining: '";&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback=',
diacritics: Array(),
newCharacters: Array(),
replaceAll: function( string, replace, replaceWith ) {
return string.replace( new RegExp( replace, 'g' ), replaceWith );
},
replaceDiacritics: function( text ) {
string = text;
// diacritics and newCharacters should be arrays of the same length
// diacritics should only be specified in lowercase - uppercased version will be assumed
// durring the process
for ( i = 0; i < this.diacritics.length; i++ ) {
string = this.replaceAll( string, this.diacritics[i], this.newCharacters[i] );
string = this.replaceAll( string, this.diacritics[i].toUpperCase(), this.newCharacters[i].toUpperCase() );
}
return string;
},
translate: function( text, target, source ) {
target = target || this.target;
source = source || this.source;
return $.ajax({
url: this.url + encodeURIComponent( this.replaceDiacritics( text ) ) + '" and source="' + source + '" and target="' + target + this.urlRemaining,
dataType: 'json',
cache: false
});
},
spitResult: function( x, container ) {
x.success(function(realData) {
$report = realData.query.results.json.sentences;
$result = '';
if ($.isArray($report)) {
for (i = 0; i < $report.length; i++) {
$result += $report[i].trans;
}
} else {
$result = $report.trans;
}
if (container instanceof jQuery) {
container.html($result);
} else {
container.innerHTML = $result;
}
});
}
}
And now I'm calling it on a set of elements in the page
promises = Array();
Translator.diacritics = Array('ă', 'â', 'î', 'ș', 'ț');
Translator.newCharacters = Array('a', 'a', 'i', 's', 't');
$('.translate').each(function() {
$this = $(this);
promises[promises.length] = Translator.translate($this.html(), 'en', 'ro');
Translator.spitResult(promises[promises.length-1], $this);
});
This is working no problem with Firefox and Chrome. However, as usual, Internet Explorer (9 in my case) seems to be the problem. From what I've been able to deduce it resides in the promise resolver (Translate.spitResult
) - which is called, but no data seem to be passed to it. I looked at it in the console. The promise array element is populated with 3 objects (which I am sure is normal), but it is:
readyState: 0
responseJSON: undefined, status: 0
statusText: "No Transfer".
I tried removing the diacritics function (now I'm not exactly sure why, because there should have been a response anyway), I also tried cache: false
mode on the ajax call, but to no avail.
Does anyone know what could be the matter ?
Thank you in advance.