我希望用户输入他们的姓名和电子邮件地址,然后在表单上点击“提交”后在页面上回显。问题是,当我点击提交时,在我的ajax2.php中找不到“email _address”和“name”。我确定我使用了错误的语法,但我无法弄清楚要改变什么。
我的表单
<label for="email_address">Email Address:</label>
<input type="text" id="email_address">
<label for="name">First Name:</label>
<input type="text" id="name">
<label> </label>
<button type='submit'>submit</button>
</form>
脚本:
$(document).ready(function(){
$("#email_form").submit(function(){
event.preventDefault();
$.ajax({
url: "include/ajax2.php",
type: 'POST',
data: $("#email_form").serializeArray(),
success: function(data){
var assArr = jQuery.parseJSON(data);
$("#output").html("Email:" +assArr['email_address'] + " Name:" + assArr['name']);
},
error: function() {
$("#output").html("Error with ajax");
}
});
});
});
ajax2.php
$assocArr = array();
$assocArr ['email_address'] = $_POST['email_address'];
$assocArr ['name'] = $_POST['name'];
echo json_encode($assocArr);
答案 0 :(得分:0)
试试这个,添加&#34; dataType:json&#34;请求:
添加元素的名称:email_address和name:
<form id="email_form" name="email_form" >
<label for="email_address">Email Address:</label>
<input type="text" id="email_address" name="email_address">
<label for="name">First Name:</label>
<input type="text" id="name" name="name">
<label> </label>
<button type='submit'>submit</button>
</form>
添加&#34; dataType:json&#34;:
<script>
$(document).ready(function () {
$("#email_form").submit(function () {
event.preventDefault();
$.ajax({
url: "include/ajax2.php",
type: 'POST',
dataType: "json",
data: $("#email_form").serializeArray(),
success: function (data) {
var assArr = jQuery.parseJSON(data);
$("#output").html("Email:" + assArr['email_address'] + " Name:" + assArr['name']);
},
error: function () {
$("#output").html("Error with ajax");
}
});
});
});
文件ajax2.php不会改变:
$assocArr = array();
$assocArr ['email_address'] = $_POST['email_address'];
$assocArr ['name'] = $_POST['name'];
echo json_encode($assocArr);
文件ajax2.php将返回:
{"email_address":"JohnDoe@gmail.com","name":"John Doe"}