0

我正在尝试使用 XMLHttpRequest 方法使用 AJAX 调用一个简单的 XML 文件,但它一直在遇到 catch 块。该方法将首先对正确的电子邮件条目进行客户端验证,然后检查外部 XML 文件中的“禁止”电子邮件地址。有人可以解释一下为什么它失败了这是代码,谢谢!

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");
        }
      }
    }
}
4

1 回答 1

0

processRequest()马上打电话。您希望将其分配给 onreadystatechange以便稍后调用它。为此,请删除括号:

request.onreadystatechange = processRequest;
于 2012-04-22T00:05:23.553 回答