gpt4 book ai didi

javascript - 将多个 ajax 请求串到一个输出中

转载 作者:行者123 更新时间:2023-12-03 01:55:34 25 4
gpt4 key购买 nike

我正在尝试翻译网页上的多个字段并将最终输出放在一起,如下所示:

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

感谢安德鲁,我能够解决这个问题,以下代码是我为遇到类似困难的人提供的最终解决方案:

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

最佳答案

实现您想要的目标的一种方法是跟踪您发送的请求数量并记录已完成的请求数量。当返回的金额与发送的金额相同时,您就可以显示数据。

当请求成功完成时,您可以将数据附加到对象或数组,这就是您将在最后显示的内容。

下面要看的主要部分是

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);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click Me</button>

编辑:我添加了如何使用 let 帮助您使用在 ajax 成功处理程序外部定义但在成功处理程序内部使用的变量。如果您看到 noLet 总是打印 3,因为 var 是函数作用域,并且当最后一个请求返回时,变量 i 已经运行过循环并且是最后一个值。

由于 let 是 block 作用域(本例中的 for 循环),因此它将保存在同一循环迭代中使用 ajax 函数时使用的 i 的值被解雇了。这是 difference between var and let 上的一个好帖子。

关于javascript - 将多个 ajax 请求串到一个输出中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50258965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com