我无法找到任何关于ajax的深入指南,特别是对于php服务器端。 我目前只尝试将数据发布到PHP并测试它,然后尝试转储到SQL。 工作了2天,仍然无法正常工作。猜猜现在是去库存溢出的好时机: HTML + JS:
<script>//send data scripts
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "php/formSubmission.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseTexts;
}
};
request.send(formData);
</script>
&#13;
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
<div>
Name: <input type="text" id="firstName" name="firstname" class="" required />
Family Name: <input type="text" id="lastName" name="lastname" class="" required />
</div>
<div>
Email: <input type="email" class="" id="email" name="email "required />
</div>
<div>
Phone Number: <input type="text" id="phone" name="phone" class="" required />
</div>
<div>
Country: <select name="country" class="countries" id="countryId" style="width: 100px">
<option value="">Select Country</option>
</select>
State: <select name="state" class="states" id="stateId">
<option value="">Select State</option>
</select>
City: <select name="city" class="cities" id="cityId">
<option value="">Select City</option>
</select>
</div>
<div>
Address: <input type="text" name="address" /><br />
</div>
<button type="submit">Submit</button>
</form>
<p id="testing"></p>
&#13;
<?php
/**
* Created by PhpStorm.
* User: user
* Date: 17-Sep-16
* Time: 14:50
*/
echo $_POST['email'];
?>
还有关于该主题的视频和书籍的任何建议吗?
答案 0 :(得分:0)
我不知道这只是你真实代码中的错字,但是
request.responseTexts
应该是
request.responseText
(最后的“s”不行)
答案 1 :(得分:0)
您需要在代码中更改一些内容,例如:
查看以下<input>
元素
<input type="email" class="" id="email" name="email "required />
^^^^^^^^^^^^^
你能看到email
之后的额外空格吗?这就是为什么在PHP方面echo $_POST['email'];
无法工作的原因。这个<input>
元素应该是这样的:
<input type="email" class="" id="email" name="email" required />
点击这里的JavaScript声明,
document.getElementById("testing").innerHTML = request.responseTexts;
^^^^^^^^^^^^^^^^^^^^^
应该是,
document.getElementById("testing").innerHTML = request.responseText;
查看顶部<form>
元素
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
但我在你的代码中看不到formValidation()
函数。创建一个名为formValidation()
的函数,并确保从该函数返回false
,否则每次单击提交按钮时都会提交表单。所以,你的脚本应该是这样的:
<script>
function formValidation(){
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "post.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseText;
}
};
request.send(formData);
return false;
}
</script>