javascript - 在表单上提交复选框值而不刷新页面 AJAX PHP
问题描述
我刚开始学习 ajax,我同意它真的很棒而且节省时间。
但是我在这一点上卡住了发送表单数据而没有重新加载页面。
下面是我的html代码。
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<p class="form-message"></p>
</form>
下面是我的 Ajax 脚本
<script>
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
var action = 'another_test';
var agreed = $("#agreed").val();
var submit = $("#form-submit").val();
$(".form-message").load("test3.php", {
test: agreed,
submit: submit,
action: action
});
});
});
</script>
下面是我的php代码
<?php
if (isset($_POST['action'])) {
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$errorEmpty = false;
if (!empty($test)) {
echo "<p>Click the checkbox pls</p>";
$errorEmpty = true;
}
else {
echo "<p>Checkbox clicked</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
php 文件位于另一个名为 test3.php 的页面上
如果它是输入文本,则此特定代码有效,但不适用于复选框。请帮助我,这样我才能学得好。提前致谢。
解决方案
.load()
(根据文档)执行 GET 请求,而不是 POST,但您的 PHP(如$_POST
参考文献所示)期待 POST 请求 - 通常使用 POST 提交表单数据是有意义的。
所以你最好使用$.post()
- 这将发送一个 POST 请求。然后您可以处理响应并将其加载到由该请求触发的“完成”回调中的“表单消息”元素中。
注意您还可以通过将“action”变量作为隐藏字段放入表单中来缩短代码,然后在一个命令中简单地序列化表单,而不是单独提取每个值。
例子:
HTML:
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<input type="hidden" action="another_test"/>
<p class="form-message"></p>
</form>
JavaScript
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
$.post(
"test3.php",
$(this).serialize()
).done(function(data) {
$(".form-message").html(data);
});
});
});
文档:
推荐阅读
- android - 安装APK Xiami Redmi A4时出错
- javascript - 在 laravel 中使用 ajax 可拖动行
- python - python中的&=后面有哪些数学或逻辑运算?
- angular - Angular 6:“Observable”类型上不存在属性“catch”
'? - php - 我正在尝试使用 fetch_assoc() 但它给出了错误未定义的方法
- wordpress - 为什么插件在我的 html 到 wordpress 转换主题中不起作用?
- ionic-framework - 我想在我的应用程序中为 android 用户提供强制更新功能
- android - Android 清单合并失败
- r - R,如何一次操作多个数据框
- python - Python - 比较两个列表 - 打印结果