首页 > 解决方案 > 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 标签中,有谁知道发生这种情况的原因是什么。谢谢

标签: phpajaxxampp

解决方案


看来,当您单击按钮以获取响应时,它还会刷新浏览器中的页面。您可以尝试以下方法来防止这种情况:

<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"按钮。

您可以在此处阅读有关我使用的功能的更多详细信息:


推荐阅读