解决这个问题,我想通过数据对象中的AJAX向PHP发送一个序列化的表单字符串。我的表格是:
<form id="add_project_form" method="post">
<div class="form_group">
<p>Title:</p>
<input type="text" name="title">
</div>
<div class="form_group form_select" id="visible">
<p>Visible:
<select name="visible">
<option>1</option>
<option>0</option>
</select>
</p>
</div>
<a href="javascript:void(0)" id="submit_project">Add Project</a>
</form>
我可以像数据一样:$('form')。serialize()但似乎无法将其传递给对象。
$('#submit_project').click(function() {
$.ajax({
url: 'ajax_calls.php',
type: 'POST',
data: {
add_project_call: true,
form_data: $('#add_project_form').serialize()
},
success: function(addedResults) {
console.log(addedResults);
}
});
});
并且,只是为了测试,从PHP获取标题
if(isset($_POST['add_project_call'])) {
$title = $_POST['title'];
$visible = $_POST['visible'];
echo $title;
}
我看到serialize将表单数据转换为字符串,但是如何访问PHP中的值?
谢谢,
答案 0 :(得分:0)
更改javascript,如:
$('#submit_project').click(function() {
var form_data = {};
$('#add_project_form').serializeArray().map(function(n){form_data[n.name] = n.value;});
$.ajax({
url: 'ajax_calls.php',
type: 'POST',
data: {
add_project_call: true,
form_data: form_data
},
success: function(addedResults) {
console.log(addedResults);
}
});
});
更改php文件(ajax_calls.php),如:
if(isset($_POST['add_project_call'])) {
$title = $_POST['form_data']['title'];
$visible = $_POST['form_data']['visible'];
echo $title;
}