从javascript多次调用ajax [英] Calling to ajax multiple times from javascript
问题描述
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.
I'm trying to call ajax multiple times to load data in a set of divs: 24 of them, they start with divTime0, divTime1, divTime2, divTime3...... divTime23. Each time its called, the value for the TimeSlot corresponds with the div e.g. TimeSlot=0 goes in divTime0.
我知道这里的ajax调用相互覆盖,但是不知道如何解决这个问题,而无需编写24个代码块来使其工作.N.B.如果我不执行for循环而单独执行,则此是有效的,但是它将仅填充24个div中的1个
I know the ajax calls here are overriding each other but have no idea how to solve it without writing out 24 blocks of code to get it working. N.B. this is working if i execute singularly without the for loop but it will just populate 1 of the 24 divs
以下代码可为24个div加载图片:
The following code worked to load 24 divs with images:
for(var x=0 ; x<=23 ; x++)
document.getElementById("timeanalysisimg"+x).src="ajax.php?id=15&AreaID=" +encodeURIComponent(AreaID);
我正在尝试做类似的事情,而不必编写不必要的代码.有什么想法吗?
I'm trying to do something similar without having to write unnecessary code. Any ideas?
我可以使用.只是粘贴解决方案
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多次调用ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!