php - PHP 响应消失
问题描述
我正在尝试通过 ajax 获得响应,我的代码(index.html):
<button id="register">Register</button>
<p id="result">xxx</p>
<script>
$("#register").click(function(){
$.ajax({
url:'registration.php',
type: 'POST',
success:function(response){
$("#result").html(response)
}
})
})
</script>
和php(registration.php):
<?php
echo "yyy"
?>
我正在使用 xampp,我得到了响应,但它会立即从页面中消失。xxx 再次出现在 p 标签中,有谁知道发生这种情况的原因是什么。谢谢
解决方案
看来,当您单击按钮以获取响应时,它还会刷新浏览器中的页面。您可以尝试以下方法来防止这种情况:
<script>
$("#register").click(function(evt) {
evt.preventDefault()
$.ajax({
url:'registration.php',
type: 'POST',
success: function (response) {
$("#result").html(response)
}
})
})
</script>
这会阻止您的浏览器在您单击按钮时执行通常的操作。<form>
标签内的任何按钮都会在当前窗口内自动发送GET
请求,从而导致页面刷新。另一种选择preventDefault()
是使用type="button"
按钮上的属性,这将阻止按钮成为type="submit"
按钮。
您可以在此处阅读有关我使用的功能的更多详细信息:
推荐阅读
- excel - wb.Worksheets("ws").Sort 开头的行上的下标超出范围
- azure - 使用 Azure API 管理服务,是否可以使用 2 种不同的身份验证方法?
- java - 电子邮件中包含多行的 Android Studio
- c# - 使用 Active Directory 和 c# 的董事或以上的所有员工
- c# - OpenQA.Selenium.WebDriverException: '不能点击元素'
- javascript - 关闭对话框时,ReactNative Alert.alert() 对话框不会触发 onDismiss 事件
- android - React-native android构建失败并出现异常
- python - 如何使用 Selenium 在重定向链末尾获取 .pdf 下载?
- api - 将 RabbitMQ 配置为通过 HTTP 端点路由到队列,因此不需要普通的 JSON 数据
- c - 如何在C中打印未知长度数组中的每个元素