首页 > 解决方案 > 链接触发 XMLHttpRequest

问题描述

我制作了一个简单的 XMLHttpRequest,它确实可以工作,它发送请求等。就像在 W3 学校中一样。

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demox").innerHTML = this.responseText;
    }
  };

  xhttp.open("POST", "textx.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("fname=" + textxx);
}

当我尝试通过单击链接来触发请求时,问题就开始了,该链接将我发送到处理请求的 php 文件。我发现在我目前的水平上很难理解为什么它不起作用,因为它适用于简单的表格等。

我得到:

"Notice: Undefined index: fname ..."

所以,我认为,这意味着变量没有被发送。有人可以解释吗?或者有没有办法调试从一页发送到另一页的东西。我发现的只是 chrome 中的一个调试器,它确实捕获了请求,但没有真正的用途,因为我被发送到 textx.php 页面并且一切都丢失了。

标签: javascripthtmlxmlhttprequest

解决方案


不太确定,您的问题可能出在哪里,也许可以尝试:

var xhttp = new XMLHttpRequest();
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.open("POST", "textx.php", true);
    xhttp.onreadystatechange = function() {
    if (this.readyState === 4){
        if(this.status===200 || this.status===0){
            document.getElementById("demox").innerHTML = this.responseText;
        }
    };

    var fname = "fname=" + textxx;
    xhttp.send(fname);
}

您可能会console.log(xhttp);看到一步一步的配置文件并找出问题可能出在哪里。


推荐阅读