gpt4 book ai didi

javascript - 从javascript多次调用ajax

转载 作者:行者123 更新时间:2023-11-30 12:51:32 25 4
gpt4 key购买 nike

for(var x=0 ; x<=23 ; x++)
{
AjaxRequest16 = null;
AjaxRequest16 = getXmlHttpRequestObject(); // method here to load the request

if(AjaxRequest16.readyState == 4 || AjaxRequest16.readyState == 0)
{
AjaxRequest16.open("GET", "ajax.php?id=16&AreaID=" +encodeURIComponent(AreaID)+ "&month="
+encodeURIComponent(document.getElementById("cboMonths").value)+ "&TimeSlot=" +encodeURIComponent(x), true);

AjaxRequest16.send(null);

AjaxRequest16.onreadystatechange = function()
{
if(AjaxRequest16.readyState == 4)
{
var innerHTML = AjaxRequest16.responseText.toString();
/* Retrieve data from the server and display. */
document.getElementById("divTime"+x).innerHTML = innerHTML;

}/* end if */
}/* end function */
}/* end if */

}/* end if */

我试图多次调用 ajax 以在一组 div 中加载数据:其中 24 个,它们以 divTime0、divTime1、divTime2、divTime3……divTime23 开头。每次调用时,TimeSlot 的值都对应于 div,例如TimeSlot=0 进入 divTime0。

我知道这里的 ajax 调用会相互覆盖,但如果不写出 24 段代码来让它工作,我不知道如何解决它。注意如果我在没有 for 循环的情况下单独执行,这工作,但它只会填充 24 个 div 中的 1 个

以下代码用于加载 24 个带有图像的 div:

for(var x=0 ; x<=23 ; x++)
document.getElementById("timeanalysisimg"+x).src="ajax.php?id=15&AreaID=" +encodeURIComponent(AreaID);

我正在尝试做类似的事情,而不必编写不必要的代码。有什么想法吗?

我成功了。直接粘贴解决方案

for(var x=0 ; x<=9 ; x++)
{
test(x, AreaID); // calling the function which resides externally to the loop
}

外部方法:

function test(x, AreaID)
{
var AjaxRequest16 = null;
AjaxRequest16 = getXmlHttpRequestObject();

if(AjaxRequest16.readyState == 4 || AjaxRequest16.readyState == 0)
{
AjaxRequest16.open("GET", "ajax.php?id=16&AreaID=" +encodeURIComponent(AreaID)+ "&month="
+encodeURIComponent(document.getElementById("cboMonths").value)+ "&TimeSlot=" +encodeURIComponent(x), true);

AjaxRequest16.send(null);

AjaxRequest16.onreadystatechange = function()
{
if(AjaxRequest16.readyState == 4)
{
var innerHTML = AjaxRequest16.responseText.toString();
/* Retrieve data from the server and display. */
document.getElementById("divTime"+x).innerHTML = innerHTML;

}
}
}
}

最佳答案

将代码块放入函数中:

for(var x=0 ; x<=23 ; x++)
{
(function(x) {
var AjaxRequest16 = getXmlHttpRequestObject();
//rest of the code

}(x));
} //end of for loop

关于javascript - 从javascript多次调用ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20801510/

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