Ajax 同时处理多个异步请求,可能出现这样的错误:只有最后一个异步请求有效,其他的都没效果。所以当我们执行完一次异步请求就应该把这次创建出来的 XMLHttpRequest 对象删除,然后再执行下一次异步请求。删除使用 delete 即可
delete xmlHttp; xmlHttp = null
下面举个示例进行说明:
index.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax 处理多个异步请求</title> </head> <body> <p>Input1:<input type="text" id="first" /> <span id="firstSpan"></span></p> <p>Input2:<input type="text" id="second" /> <span id="secondSpan"></span></p> <p>Input3:<input type="text" id="three" /> <span id="threeSpan"></span></p> <p><input type="button" value="发送" οnclick="test();" /></p> </body> </html> <script language="javascript"> function getData(url, input, label) { var xmlHttp; if (window.ActiveXObject) { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } var val = document.getElementById(input).value; var realUrl = url + "?time=" + new Date().getTime() + "&text=" + val; realUrl = encodeURI(encodeURI(realUrl)); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState==4 && xmlHttp.status==200) { var labelSpan = document.getElementById(label); labelSpan.innerHTML = decodeURI(xmlHttp.responseText); delete xmlHttp; // 手动删除 xmlHttp = null } } xmlHttp.open('GET', realUrl); xmlHttp.send(null); } function test() { getData('index.php', 'first', 'firstSpan'); getData('index.php', 'second', 'secondSpan'); getData('index.php', 'three', 'threeSpan'); } </script>
index.php
<?php header('Content-Type:text/html;Charset=utf-8'); echo $_GET['text']; ?>
效果展示图:
下面举个示例进行说明:
index.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax 处理多个异步请求</title> </head> <body> <p>Input1:<input type="text" id="first" /> <span id="firstSpan"></span></p> <p>Input2:<input type="text" id="second" /> <span id="secondSpan"></span></p> <p>Input3:<input type="text" id="three" /> <span id="threeSpan"></span></p> <p><input type="button" value="发送" οnclick="test();" /></p> </body> </html> <script language="javascript"> function getData(url, input, label) { var xmlHttp; if (window.ActiveXObject) { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } var val = document.getElementById(input).value; var realUrl = url + "?time=" + new Date().getTime() + "&text=" + val; realUrl = encodeURI(encodeURI(realUrl)); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState==4 && xmlHttp.status==200) { var labelSpan = document.getElementById(label); labelSpan.innerHTML = decodeURI(xmlHttp.responseText); delete xmlHttp; // 手动删除 xmlHttp = null } } xmlHttp.open('GET', realUrl); xmlHttp.send(null); } function test() { getData('index.php', 'first', 'firstSpan'); getData('index.php', 'second', 'secondSpan'); getData('index.php', 'three', 'threeSpan'); } </script>
index.php
<?php header('Content-Type:text/html;Charset=utf-8'); echo $_GET['text']; ?>
效果展示图:
