Ajax XHTTP请求不起作用

Ajax XHTTP Request wont work

本文关键字:不起作用 请求 XHTTP Ajax      更新时间:2023-09-26

我已经被困在这个问题上一段时间了,请帮助。

我正在尝试执行XHTTP请求,解析?(这是正确的术语)XML文档。请求不会进入myFunction(xml),我不知道为什么,它响应200 ok,所以应该是好的?

请求应该检查XML中是否有在HTML表单中输入的电子邮件,如果找到,则相应地响应。

感谢任何帮助!!

下面的Javascript:

<script type="text/javascript">
function loadDoc()
{
email = document.getElementById('email');
password = document.getElementById('password');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() 
{
    if (xhttp.readyState == 4 && xhttp.status == 200) 
    {
        myFunction(xhttp);
    }
}
}
xhttp.open("POST", "customer.xml", true);
xhttp.send();
function myFunction(xml) 
{
var x, i, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("email");
for (i = 0; i < x.length; i++) 
{ 
    if (x[i].nodeValue == document.getElementById('email')) 
    {
        return (true);
        alert('Success, you have logged in!');
    }
    else
    {
        alert('Failed to log in');
        document.myForm.email.focus();
        return false;
    }
 }
}
</script>
XML:
<?xml version="1.0" encoding="UTF-8"?>
<customers>
<customer>
  <custid />
  <firstname />
  <lastname />
  <email />
  <password />
  <phone />
</customer>
<customer>
  <custid>562b5d237b599</custid>
  <firstname>1</firstname>
  <lastname>1</lastname>
  <email>1</email>
  <password>1</password>
  <phone>1</phone>
</customer>
<customer>
  <custid>562b62824e3f7</custid>
  <firstname>ben</firstname>
  <lastname>1</lastname>
  <email>1</email>
  <password>1</password>
  <phone>1</phone>
</customer>
<customer>
   <custid>562b63224b80f</custid>
  <firstname>ben</firstname>
  <lastname>ben</lastname>
  <email>ben@gmail.com</email>
  <password>ben</password>
  <phone>0266746374</phone>
</customer>
<customer>
  <custid>562b68ea06ed1</custid>
  <firstname>mark</firstname>
  <lastname>mark</lastname>
  <email>mark@gmail.com</email>
  <password>mark</password>
  <phone />
 </customer>
 </customers>
}
xhttp.open("POST", "customer.xml", true);
xhttp.send();

这里您尝试在创建它的函数之外使用xhttp 。注意你把}放在哪里(更小心你如何缩进你的代码会使这更明显)。

x[i].nodeValue == document.getElementById('email')

那永远不会是真的。getElementById将返回一个HTML元素节点,而不是字符串。假定您正在寻找.value

当你调试你的代码时,你需要检查你正在测试的值,看看它们是否真的匹配。

else
{
    alert('Failed to log in');
    document.myForm.email.focus();
    return false;
}

和这里,如果第一个节点值不匹配,那么你立即return,所以你不测试任何其他。

你需要把失败的条件放在循环之外,这样它只有在你没有得到匹配时才会触发。


这个系统当然是完全不安全的,因为任何人都可以请求XML文件并读取其中的密码。