这就是我所拥有的,大约 80% 的时间它都能工作,但每隔一段时间它就会崩溃。可以更好地将这些结合起来吗?或者至少在显示之前检查两者是否都返回了有效结果。我尝试设置为两个单独的函数并串联运行它们,但由于某种原因这也不起作用。如果可能的话我想避免使用 jQuery。谢谢
function doit(str){
var color = document.getElementById('button').value;
if (str == "") {
document.getElementById("Div1").innerHTML = "";
document.getElementById("Div2").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
ajaxRequest = new XMLHttpRequest();
ajaxRequesttwo = new XMLHttpRequest();
} else {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
ajaxRequesttwo = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
document.getElementById("Div1").innerHTML = ajaxRequesttwo.responseText;
document.getElementById("Div2").innerHTML = ajaxRequest.responseText;
}
}
ajaxRequesttwo.open("GET","ajax/page1.php?r="+str+"&c="+color,true);
ajaxRequest.open("GET","ajax/page2.php?q="+str,true);
ajaxRequesttwo.send();
ajaxRequest.send();
}
}
最佳答案
如果我理解正确的话,你想执行两个AJAX请求,并在两个请求完成后将输出设置到两个div。
选项1:只让最新的AJAX请求处理程序(可以是任一请求)进行输出显示。
function doitnow(str) {
// DOM elements / values
var div1 = document.getElementById("Div1");
var div2 = document.getElementById("Div2");
var color = document.getElementById('button').value;
// reset results
if (str == "") {
div1.innerHTML = "";
div2.innerHTML = "";
return;
}
// Prepare AJAX requests & handlers
var ajaxRequest1 = new XMLHttpRequest();
var ajaxRequest2 = new XMLHttpRequest();
var result1, result2; // to store results of requests
ajaxRequest1.onreadystatechange = function() {
if (ajaxRequest1.readyState == 4 && ajaxRequest1.status == 200) {
result1 = ajaxRequest1.responseText;
attemptDisplay();
}
};
ajaxRequest2.onreadystatechange = function() {
if (ajaxRequest2.readyState == 4 && ajaxRequest2.status == 200) {
result2 = ajaxRequest2.responseText;
attemptDisplay();
}
};
function attemptDisplay() {
// display only if both results are set
if (typeof result1 !== 'undefined' && typeof result2 !== 'undefined') {
div1.innerHTML = result1;
div2.innerHTML = result2;
}
}
// Fire AJAX
ajaxRequest2.open("GET","ajax/page1.php?r="+str+"&c="+color,true);
ajaxRequest1.open("GET","ajax/page2.php?q="+str,true);
ajaxRequest2.send();
ajaxRequest1.send();
} //doitnow()
这应该有效。我没有做令人厌恶的 ActiveXObject 事情,因为实际上,开发人员真的不应该在应用程序的核心中进行这种类型的跨浏览器“polyfilling”。使用适当的 XHR polyfill,从此以后,您可以假装旧版 MS IE 的 AJAX 构造不存在。我推荐:https://github.com/Financial-Times/polyfill-service/blob/master/polyfills/XMLHttpRequest/polyfill.js
选项 2:ES-6 Promise
我知道您不热衷于 jQuery(可能还有其他库),但如果您不介意使用 ES-6 Promises 填充您的环境,那么这也可以是一个优雅的解决方案,特别是通过使用 Promise.all
。它本质上与选项 1 的想法相同,但被更干净的 Promise 接口(interface)抽象化了。
关于javascript - 无需 jQuery 即可组合两个 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818972/