PHP响应逐渐消失

Gor*_*rle 0 php xampp ajax

我试图通过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>
Run Code Online (Sandbox Code Playgroud)

和php(registration.php):

<?php 
echo "yyy"
?>
Run Code Online (Sandbox Code Playgroud)

我正在使用xampp,得到响应,但它会立即从页面消失。xxx再次出现在p标签中,有人知道这是什么原因吗?谢谢

pre*_*nds 5

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

<script>
$("#register").click(function(evt) {
  evt.preventDefault()

  $.ajax({
    url:'registration.php',
    type: 'POST',
    success: function (response) {
      $("#result").html(response)
    }
  })
})
</script>
Run Code Online (Sandbox Code Playgroud)

这会阻止浏览器执行单击按钮时的正常操作。<form>标记内的任何按钮都会自动GET在当前窗口内发送请求,从而刷新页面。另一种替代方法preventDefault()是使用type="button"按钮上的属性,这将阻止该按钮成为type="submit"按钮。

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