javascript - 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>
解决方案
如果您正在进行 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>
推荐阅读
- legend - Vega - 独特图表上的多个图例
- java - 为什么我无法正确预览抽屉式导航菜单?
- c# - Program.Main(string[])' 的签名错误,无法作为项目的入口点格式
- javascript - pdf.js - javascript 中的页面淡入/淡出效果
- android - 使用 DataBinding 时在 TabLayout 中显示图标和文本
- php - 我可以在 post 方法表单中从数据库中获取数据吗?
- css - 在 MVC 中将 CSS 应用于布局页面
- c# - 从父视图模型派生的空视图模型是否存在问题?WPF
- javascript - scrollHeight 和 offsetheight 给出未定义的值
- vim - 在 vim 中查找并用星号 (*) 替换