[英]ajax call not working propely in IE11 and chrome
該計划很簡單,javascript將ajax GET請求發送到文件'localhost / test / php / test.php?a ='。 test.php文件只是回顯$ _GET ['a']。 然后將Ajax響應用作div的innerHTML。
這個工作效果很漂亮,並且在firefox上可以預期,但是在Chrome和IE11上,它只是在循環的最后一次迭代中加載頁面:
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='Type=text/html; charset=utf-8'>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
Text will appear here:
<div></div>
<script src="js/script.js"></script>
</body>
</html>
使用Javascript
window.onload = function () {
test.init();
};
var test = {
init: function () {
var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
for ( var a = 0 ; a < 100 ; a++) {
ajax.open('GET','php/test.php?a='+a,false);
ajax.send();
ajax.onreadystatechange = function () {
if (this.status == 200 && this.readyState == 4) {
var div = document.getElementsByTagName('div');
div[0].innerHTML = ajax.responseText;
}
};
}
}
};
PHP
<?php
$a = $_GET['a'];
echo $a;
?>
我需要更改什么才能使其在IE和Chrome上正常運行?
您應該在循環中每次都創建一個新的XHR,而不是重復使用同一XHR。
var test = {
init: function () {
for ( var a = 0 ; a < 100 ; a++) {
var ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
ajax.open('GET','php/test.php?a='+a,false);
ajax.send();
ajax.onreadystatechange = function () {
if (this.status == 200 && this.readyState == 4) {
var div = document.getElementsByTagName('div');
div[0].innerHTML = this.responseText;
}
};
}
}
};
請注意,我還將ajax.responseText
更改為this.responseText
。 在回調中,由於Java臭名昭著的Loop問題 , ajax
將是最后創建的XHR,而不是此響應所引用的XHR ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.