当我运行我的页面时,只有 1 个 ajax 开始工作...我很确定它与 setInterval“属性”有关...
<script>
function encontrarnumero() {
src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
var divid = 'u219-4';
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
setInterval(encontrarnumero, 1000);
}
};
xmlhttp.open("GET", "numero.php?q=" + q + "&p=" + p + "&w=" + w, true);
xmlhttp.send();
}
window.onload = function () {
encontrarnumero();
};
</script>
<script>
function encontrartiempo() {
src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
var divid = 'tiempo';
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
setInterval(encontrartiempo, 2000);
}
};
xmlhttp.open("GET", "tiempo.php?q=" + q + "&p=" + p + "&w=" + w, true);
xmlhttp.send();
}
window.onload = function () {
encontrartiempo();
};
</script>
有什么想法吗?谢谢!! 附注我确定问题不是 php 文件,当我单独运行每个 ajax 时,它们工作正常。
最佳答案
重复代码过多。如果将代码重构为单个函数,事情就会简单得多。
<script>
// Move repeating code to a function
function doAJAX(divid, page) {
if (window.XMLHttpRequest) {
// Use `var` when declaring variables
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
// Use `setTimeout` if you're going to make recursive calls!
setTimeout(function() {
doAJAX(divid, page)
}, 1000);
}
};
xmlhttp.open("GET", page + "?q=" + q + "&p=" + p + "&w=" + w, true);
xmlhttp.send();
}
// Just one onload handler that calls the function twice,
// passing the different info for each call
window.onload = function () {
doAJAX('u219-4', "numero.php");
doAJAX('tiempo', "tiempo.php");
};
</script>
关于javascript - 2 AJAX 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16928750/