Javascript 解析后如何比较两个ajax响应
我在一个函数中编写了两个页面的ajax调用,是否有其他方法来编写代码,我还想比较这两个ajax响应,即比较y2和y3对象Javascript 解析后如何比较两个ajax响应,javascript,ajax,Javascript,Ajax,我在一个函数中编写了两个页面的ajax调用,是否有其他方法来编写代码,我还想比较这两个ajax响应,即比较y2和y3对象 function compareResponses() { alert('comp'); // Getting object of ORIGINAL data if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhtt
function compareResponses() {
alert('comp');
// Getting object of ORIGINAL data
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
y = xmlhttp.responseText;
alert(y);
y2 = JSON.parse(y);
}
}
xmlhttp.open("POST", "2.ashx", true);
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
// Getting object of another data
if (window.XMLHttpRequest) {
xmlhttp1 = new XMLHttpRequest();
} else {
xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange = function () {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
y1 = xmlhttp1.responseText;
//alert(y1);
y3 = JSON.parse(y1);
}
xmlhttp1.open("POST", "1.ashx", true);
xmlhttp1.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlhttp1.send();
}
为此,您需要使用承诺,因为您不知道这两个ajax调用何时(甚至是否)完成 实施示例(适应您的场景): 更多信息: 编辑:来自另一个博客的另一个链接,该链接与您的问题相同:
是否要检查它们是否相等?函数缺少一个右括号。如果要同时发送两个AJAX请求,我认为需要使用承诺等待两个请求完成。相反,您可以连续发送它们。让第一个请求的回调函数发出第二个请求,第二个回调可以比较响应。
// Promise to be filled with future value
var futureValue = new Promise();
// .then() will return a new promise
var anotherFutureValue = futureValue.then();
// Promise state handlers ( must be a function ).
// The returned value of the fulfilled / failed handler will be the value of the promise.
futureValue.then({
// Called if/when the promise is fulfilled
fulfilledHandler: function() {},
// Called if/when the promise fails
errorHandler: function() {},
// Called for progress events (not all implementations of promises have this)
progressHandler: function() {}
});