2012-04-22 163 views
0

我想用AJAX使用XMLHttpRequest方法調用一個簡單的XML文件,但它會一直打到catch塊。該方法將首先爲適當的電子郵件條目進行客戶端驗證,然後檢查外部XML文件以查找「禁止的」電子郵件地址。有人可以點亮一下它爲什麼失敗這是代碼和謝謝!客戶端XMLHttpRequest問題

function validateEmail() { 

var email = document.forms["feedback"]["email"].value; 
var atpos = email.indexOf("@"); 
var dotpos = email.lastIndexOf("."); 
var url = "ajaxtest.xml"; 


// validates the format of the email address 
    if (atpos < 1 || 
    dotpos < atpos + 2 || 
    dotpos + 2 >= email.length){ 

    document.getElementById('emailmsg').innerHTML = "Gotta get this right!"; 
    document.forms["feedback"]["email"].focus(); 
    return false; 
    } else { 
    getXML(url) 
    } 
} 
function getXML(url) { 

    try { 
var request = new XMLHttpRequest(); 

    request.onreadystatechange = processRequest(); 
    request.open('GET', url, true); 
    request.send(null); 

} 
catch (e) 
    { 
    alert('Request Failed'); 
    } 
} 
function processRequest() { 

    if (request.readyState == 4 && request.status == 200) { 

    var XMLobject = request.responseXML; 
var emails = XMLobject.getElementsByTagName("email"); 

    for (var i = 0; i < emails.length; i++) { 

     var badEmails = emails.item(i); 
     var badEmail = badEmails.value; 

     if (badEmail == email) { 

     document.getElementById('emailmsg').innerHTML = "You are a bad man!"; 
     } else { 
     alert("not on the naughty list"); 
     } 
     } 
    } 
} 

回答

0

您正在打電話給processRequest()。您想將其分配給onreadystatechange,以便稍後調用它。爲此,請刪除括號:

request.onreadystatechange = processRequest;