2 つ (またはそれ以上) の ajax 呼び出しを同時に行おうとしています。jQuery は使用したくありません。純粋な JavaScript のみを使用します。
ほとんどの場合、それは機能します。data1 は sample.com/ajax1 からデータを出力し、data2 は sample.com/ajax2 からデータを出力しますが、(10 から 1) 2 番目の AJAX 呼び出しが最初の結果を表示することがあります。
なぜこうなった?どちらの AJAX 要求も、同じドメインからのデータを要求していますが、異なる URL からのものです。この動作を防ぐ方法はありますか?
スクリプトは次のとおりです。
// First AJAX
var xmlhttp1;
// Second AJAX
var xmlhttp2;
if (window.XMLHttpRequest) {
xmlhttp1 = new XMLHttpRequest();
} else {
xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange = function() {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
data = JSON.parse(xmlhttp1.responseText);
console.log('data1: ' + data);
}
}
xmlhttp1.open("GET", "http://sample.com/ajax1", true);
xmlhttp1.send();
if (window.XMLHttpRequest) {
xmlhttp2 = new XMLHttpRequest();
} else {
xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
data = JSON.parse(xmlhttp2.responseText);
console.log('data2: ' + data);
}
}
xmlhttp2.open("GET", "http://sample.com/ajax2", true);
xmlhttp2.send();