我试图使用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");
}
}
}
}
答案 0 :(得分:0)
您正在立即致电processRequest()
。您希望将其分配给onreadystatechange
,以便稍后调用它。为此,请删除括号:
request.onreadystatechange = processRequest;