AJAX请求失败

时间:2018-06-20 22:30:26

标签: javascript php html css ajax

UIAlert
function ajax() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
      alert(this.responseText);
    }
  };
}
xhttp.open("POST", "abcdef.xyz/abc/logincheck.php?mail=abc@gmail.com&password=abc", true);
xhttp.send();

我有一个如上所述的代码,而ajax操作确实导致失败。我的代码有什么问题? p中的文本永不更改。php文件的启动像这样:

    <p id="demo">
    The content of the body element is displayed in your browser.
    </p>
    <button onclick="ajax()">
    Click on me!
    </button>

2 个答案:

答案 0 :(得分:3)

xhttp.open()xhttp.send()必须位于ajax()函数中。

function ajax() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
      alert(this.responseText);
    }
  };
  xhttp.open("POST", "abcdef.xyz/abc/logincheck.php?mail=abc@gmail.com&password=abc", true);
  xhttp.send();
}

答案 1 :(得分:0)

由于xhttp.open和send在功能块的外部定义。

xhttp.open("POST", "abcdef.xyz/abc/logincheck.php?mail=abc@gmail.com&password=abc", true);
xhttp.send();