首页 > 解决方案 > AJAX 发送到 php 控制器在 javascript 中不起作用

问题描述

该片段显示了我的 html 和 js。在我的 php 控制器中,我只是 print_r($_POST) 但我只看到 myName 的表单数据我不知道如何访问 zzz

更新:我添加了一些代码以确保发送请求完成。但是,如果我不提交表单,控制器不会仅通过发出 xhttp 请求来执行。我仍然无法将任何 js 数据导入 php。我可以创建隐藏的输入并从 js 和提交中填写,但这看起来很难看。有人可以帮忙吗?

function swagSend() {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();

  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("zzz=" + henry);

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {

      document.getElementById("myForm").submit();

    }
  }
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname'>
  <button type='submit' value='submit' onClick=swagSend();>Submit</button>

</form>

标签: javascriptphpajax

解决方案


如果您正在进行 Ajax 调用,则没有理由提交表单。去掉它。

如果您希望在 Ajax 调用中提交表单数据,您需要读取表单输入值并自己构建列表。

function swagSend(event) {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  var name = encodeURIComponent(document.getElementById("myname").value)
  xhttp.send("zzz=" + henry + '&myname=' + name);
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname' id='myname'>
  <button type='submit' value='submit' onClick="swagSend(event)">Submit</button>

</form>

推荐阅读