【发布时间】:2020-09-03 10:42:48
【问题描述】:
我的目标是,当表单中的任何复选框未选中/选中时,复选框值将自动发送到 PHP 文件以过滤 SQL 数据库并更新 HTML 页面的某个部分(无需重新加载页面)。步骤:
- 检查何时在 JavaScript 中提交表单。
- 阻止页面加载。
- 对表单数据使用 serializeArray。
- 将数据转换为 JSON 字符串。
- 通过ajax传递给php文件。
- php 文件将回显传递的数据。 (用于调试)
我的问题:
- 通过 ajax 传递的数据为空。即使数据成功转换为 JSON 字符串,也没有任何通过。或者它给出了一个解析错误。
- 由于我的表单已经从 POST 数据创建了数组,我不确定是否需要 serializeArray。如果没有,我将如何传递数据?
以下是我的 HTML 代码的 sn-p,其中包含一些从 MySQL 数据库中提取数据的 PHP。
<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(); ?>
这是我在 HTML 正文页脚下的 Javascript 代码:
$(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']);
}
?>
在 Chrome 中检查控制台和警报时,在 JSON.stringify 之后,我收到以下警报:
[{"name":"category[]","value":"4"},{"name":"age[]","value":"3"},{"name":"age[]","value":"4"}] 对应于我选择的复选框。
但是,$.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)
如果我删除 dataType: 'json',我会在 console.log 中成功,但我的警报是空白的,所以没有数据通过。我也得到了
Notice: Undefined index: data in ...\includes\ajax_functions.php
【问题讨论】:
标签: javascript php html jquery ajax