这是我做的一个类,它用YQL做谷歌翻译。
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;
}
});
}
}现在我在页面中的一组元素上调用它
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);
});这对火狐和Chrome没什么问题。然而,像往常一样,(在我的例子中是9)似乎是问题所在。据我所能推断,它驻留在承诺解析器(Translate.spitResult)中,它被调用,但似乎没有数据传递给它。我在控制台里看了看。诺言数组元素填充了3个对象(我确信这是正常的),但它是:
readyState: 0
responseJSON: undefined, status: 0
statusText: "No Transfer".我尝试删除diacritics函数(现在我不确定为什么,因为无论如何都应该有一个响应),我也尝试了ajax调用的cache: false模式,但是没有效果。
有人知道怎么回事吗?
提前谢谢你。
发布于 2016-08-24 13:53:02
是的,is是你的问题.检查http://caniuse.com/#search=promise
我认为你可以使用一个多边形填充(https://github.com/taylorhakes/promise-polyfill),如果这是问题所在,从来没有尝试过一个多边形填充的承诺,但它肯定会像一个魅力。
https://stackoverflow.com/questions/19977131
复制相似问题