我正在尝试翻译网页上的多个字段,并将最终输出组合在一起,如下所示:
NOT AN OFFICIAL TRANSLATION. FOR REFERENCE USE ONLY.
Field_Name: Translation
Field_Name2: Translation
Field_Name3: Translation
来自python繁重的背景,只有很少的javascript经验,我发现这非常困难。以下代码完成85%-90%。我成功地抓住了字段名称和文本,调用了翻译api并返回了翻译。我的问题是将它串在一起作为一个警报而不是每个翻译的单独警报。由于ajax的性质,我理解在异步请求之外返回数据很困难。我认为我在ajax请求中调用另一个函数是在正确的轨道上,但我想知道是否有更好的方法来做到这一点。
//Gathers all the field names and text associated with them.
$(document).ready(function() {
var allSpans = document.getElementsByTagName('span');
var spanlist = [];
var x = 0;
var ajax_data = [];
var fieldlabels = [];
[].slice.call(allSpans).forEach(function(span) {
if(span.className === 'readonlyfield') {
if(span.textContent) {
var spanobject = {};
var textfrom = 'en';
var textto = 'it';
var text = span.innerText;
var parentelem = document.getElementById(span.parentNode.id);
var parenttext = parentelem.innerText;
fieldlabels.push(parenttext + ': ');
spanobject.parentfield = span.parentNode.id;
spanobject.parenttext = parenttext;
spanobject.textfrom = textfrom;
spanobject.textto = textto;
spanobject.text = text;
spanlist.push(spanobject);
x++;
}
}
});
var translatebutton = document.createElement('button');
translatebutton.setAttribute("id", x);
translatebutton.innerText = 'Translate!';
document.body.appendChild(translatebutton);
var finaloutput = "FOR REFERENCE USAGE ONLY. NOT AN OFFICIAL TRANSLATION." + '\n';
// On button click translate all text gathered and alert the final output.
$("button").click(function(){
var outputdata = [];
for(var i = 0, len = spanlist.length; i < len ; i++){
var textfrom = spanlist[i].textfrom;
var textto = spanlist[i].textto;
var text = spanlist[i].text;
var urlservice = 'MYTRANSLATIONURL==&text='+text+'&textfrom='+textfrom+'&textto='+textto;
jQuery.support.cors = true;
$.ajax({
url: urlservice,
type: 'GET',
contentType: "text/html",
success: function (data) {
getsomedata(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
function getsomedata(data) {
alert(data);
// The code below does not work, I was experimenting with an idea.
// ajax_data.push(data + '\n');
}
// var temp = fieldlabels.concat(ajax_data);
// temp.toString();
};
});
});
感谢Andrew我能够解决这个问题,以下代码是我遇到类似困难的人的最终解决方案:
$(document).ready(function() {
var allSpans = document.getElementsByTagName('span');
var spanlist = [];
var x = 0;
[].slice.call(allSpans).forEach(function(span) {
if(span.className === 'readonlyfield') {
if(span.textContent) {
var spanobject = {};
var textfrom = 'en';
var textto = 'it';
var text = span.innerText;
var parentelem = span.parentNode.id;
//REGEX to find field captions in my particular system.
var captionID = parentelem.replace(/((TD))?/, "TDCAP");
var captionelem = document.getElementById(captionID);
var caption = captionelem.innerText;
spanobject.spanparent = span.parentNode.id;
spanobject.captionfield = captionelem;
spanobject.caption = caption;
spanobject.textfrom = textfrom;
spanobject.textto = textto;
spanobject.text = text;
spanlist.push(spanobject);
x++;
}
}
});
var translatebutton = document.createElement('button');
translatebutton.setAttribute("id", x);
translatebutton.innerText = 'Translate!';
document.body.appendChild(translatebutton);
var finaloutput = "FOR REFERENCE USAGE ONLY. NOT AN OFFICIAL TRANSLATION." + '\n';
$("button").click(function(){
var outputdata = [];
var completedRequests = 0;
for(var i = 0, len = spanlist.length; i < len ; i++){
var textfrom = spanlist[i].textfrom;
var textto = spanlist[i].textto;
var text = spanlist[i].text;
let parentLet = spanlist[i].spanparent;
let textLet = spanlist[i].text;
let captionfield = spanlist[i].captionfield;
let caption = spanlist[i].caption;
var urlservice = 'MYTRANSLATIONURL==&text='+text+'&textfrom='+textfrom+'&textto='+textto;
jQuery.support.cors = true;
$.ajax({
url: urlservice,
type: 'GET',
contentType: "text/html",
success: function (data) {
datastring = caption + ": " + data;
outputdata.push(datastring);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
},
complete: function() {
if (++completedRequests >= len) {
getsomedata(outputdata);
}
}
});
function getsomedata(data) {
var finaldata = data.join("\n\n");
final = finaloutput + '\n' + finaldata;
alert(final);
}
};
});
});
答案 0 :(得分:1)
实现目标的一种方法是跟踪您要发送的请求数量,并记录完成的请求数量。当返回相同的金额时,您将显示数据。
请求成功完成后,您可以将数据附加到对象或数组,这就是您最后要显示的内容。
下面要看的主要部分是
if (++completedRequests >= len) {
getsomedata(outputdata)
}
每次ajax请求完成(成功或失败)时, completedRequests
都会递增。当该数量与循环的长度相同时,我们知道我们已经完成并且可以显示我们的数据。
警告:不要期望以任何特定的顺序返回数据,它是异步的,因此请求在完成时返回,而不是与发送它们的顺序相同
var spanlist = [0, 0, 0, 0]; // example placeholder
$("button").click(function() {
var outputdata = [];
var completedRequests = 0;
for (var i = 0, len = spanlist.length; i < len; i++) {
var noLet = i;
let yesLet = i;
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/" + (i + 1),
type: 'GET',
success: function(data) {
outputdata.push(data.id);
// These console logs are to explain how let is used with this ajax inside a loop
console.log("noLet: " + noLet);
console.log("yesLet: " + yesLet);
},
error: function(xhr, status, errorThrown) {
console.error(status + '\n' + JSON.stringify(xhr) + '\n' + errorThrown);
},
complete: function() {
if (++completedRequests >= len) {
getsomedata(outputdata)
}
}
});
}
});
function getsomedata(data) {
alert(data);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click Me</button>
&#13;
编辑:我添加了如何使用let
来帮助您使用在ajax成功处理程序之外定义但在成功处理程序中使用的变量。如果您看到noLet
打印3总是因为var
是函数作用域,并且在最后一个请求返回时,变量i
已经遍历循环并且是最后一个值。
因为let
是块作用域的(本例中为for循环),所以它将保存在同一循环迭代中的ajax函数被触发时使用的i
值。这是difference between var
and let