我的目标是,当未选中/选中表单中的任何复选框时,复选框值将自动发送到PHP文件以过滤SQL数据库并更新HTML页面的特定部分(而无需重新加载页面)。步骤:
- 检查何时使用JavaScript提交表单。
- 防止页面加载。
- 在表单数据上使用serializeArray。
- 将数据转换为JSON字符串。
- 通过ajax传递到php文件。
- php文件将回显传递的数据。 (用于调试)
我的问题:
- 通过ajax传递的数据为空。即使数据已成功转换为JSON字符串,也不会通过。或给出解析错误。
- 由于我的表单已经根据POST数据创建了数组,因此我不确定serializeArray是否必要。如果没有,我将如何传递数据?
以下是我的HTML代码的片段,其中包含一些PHP,这些PHP从MySQL数据库中提取数据。
<form id="selectors" method="POST">
<div class="selector-title">Categories</div>
<?php foreach ($categories as $category): ?>
<input type='checkbox' name='category[]' value='<?php echo $category['category_id'] ?>' id='selector1'><i class="fas fa-<?php echo $category['category_icon'] ?>"></i> <?php echo $category['category_title'] ?>
<?php endforeach ?>
<div class="selector-title">Age</div>
<?php foreach ($ages as $age): ?>
<input type='checkbox' name='age[]' value='<?php echo $age['age_id'] ?>' id='selector2'><i class="fas fa-<?php echo $age['age_icon'] ?>"></i> <?php echo $age['age_range'] ?>
<?php endforeach ?>
<input type="submit">
</form>
<?php getGiftsInCategories(); ?>
这是我的Javascript代码,位于HTML正文的页脚下:
$(document).ready(function(){
$("form").on("submit", function(e){
e.preventDefault();
alert("Page prevented from loading. In function.")
var data = $('form').serializeArray(); //necessary? if $_POST is already in an array?
var JSONData = JSON.stringify(data); //convert array to string
alert(JSONData);
var type = typeof JSONData;
alert(type);
$.ajax({
url: "includes/ajax_functions.php",
type: "POST",
async: true,
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: {data : JSONData},
success: function(data){
alert(data);
console.log("success");
},
error: function (request, status, error) {
console.log(status);
console.log(request.responseText);
console.log(error);
}
});
});
})
和我的ajax_functions.php:
<?php
function getGiftsInCategories() {
echo $data = json_decode($_POST['data']);
}
?>
When checking the console and alerts in Chrome, after JSON.stringify, I get this alert:
[{"name":"category[]","value":"4"},{"name":"age[]","value":"3"},{"name":"age[]","value":"4"}]
which corresponds with the checkboxes I selected.
但是,$。ajax失败,出现此错误:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at n.parseJSON (jquery.min.js:4)
at vc (jquery.min.js:4)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
If I remove dataType: 'json'
, I get success in the console.log, but my alert is blank, so no data has passed. I also get
Notice: Undefined index: data in ...\includes\ajax_functions.php
PHP不知道如何解码JSON编码的HTTP请求…
… but you're passing an object to
data
, not a string of JSON, so the content-type is a lie.删除contentType行。