我正在尝试创建一个脚本,允许我用几行代码进行 ajax 调用。该脚本适用于一个 ajax 请求,但在一次处理多个请求时它会失败。我做错了什么?
该代码只处理最后一个请求,而让其他请求“加载......”。
这是我的代码:
/****************
Related Javascript inside the HTML document
****************/
// First request
var ajax1 = new ajax_class();
ajax1.meth = "GET";
ajax1.file = "ajax_info.txt";
ajax1.elem = "results";
ajax1.send = null;
ajax1.ajax_call(ajax1.meth, ajax1.file, ajax1.elem, ajax1.send);
...
// Third request
var ajax3 = new ajax_class();
ajax3.meth = "GET";
ajax3.file = "ajax_info3.txt";
ajax3.elem = "results3";
ajax3.send = null;
ajax3.ajax_call(ajax3.meth, ajax3.file, ajax3.elem, ajax3.send);
/****************
Related HTML inside the HTML document
****************/
<body>
<div id="results">Nothing has happend yet for 1....</div>
<div id="results2">Nothing has happend yet for 2 ....</div>
<div id="results3">Nothing has happend yet for 3 ....</div>
</body>
/****************
Related code inside the JAVASCRIPT document
****************/
function ajax_class () {
this.meth = "GET";
this.file;
this.elem;
this.send = null;
this.ajax_call = function (meth, file, elem, send) {
x = new XMLHttpRequest();
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200) {
_id(elem).innerHTML = x.responseText;
}
else {
_id(elem).innerHTML = "Loading ...";
}
}
x.open(meth , file, true);
x.send(send);
}
}
现在可以工作了,只需要在 x 变量前面添加“var”