2014-03-12 39 views
0

我不得不寫在單一功能的兩頁的Ajax調用後二Ajax響應比較是沒有任何替代方法來編寫代碼,這個也是我想比較這兩個Ajax響應,即,比較這兩個Y2和Y3對象。如何解析

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(); 
    } 
+0

你想檢查它們是否平等嗎? –

+0

您錯過了該功能的右大括號。 – Barmar

+1

如果你想同時發送兩個AJAX請求,我認爲你需要使用的承諾,等待他們倆來完成。相反,你可以連續發送它們。第一個請求的回調函數發出第二個請求,第二個回調函數可以比較響應。 – Barmar

回答

0

您需要爲此使用promise,因爲您不知道何時(或甚至IF)都會完成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() {} 
}); 

更多信息:http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

編輯:

http://www.html5rocks.com/en/tutorials/es6/promises/

:從具有相同的問題,因爲你的另一個博客另一個鏈接