【发布时间】:2020-11-02 19:36:44
【问题描述】:
我刚开始学习 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() (根据documentation 执行 GET 请求,而不是 POST。要提交数据,您最好使用 $.post()
-
php 文件在另一个页面上
-
这与我的观点无关。您的 PHP 脚本需要一个 POST,而您正在向它发送一个 GET。这是否与加载到浏览器中的脚本不同,这对这一事实没有影响。 api.jquery.com/jquery.post 是你需要使用的。
-
好的会检查一下谢谢
-
下面我给你举个例子,你看看
标签: javascript php jquery ajax