weixin_33736649 2018-10-04 12:16 采纳率: 0%
浏览 18

PHP响应逐渐消失

I am trying to get response trough ajax,my code (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>

and php (registration.php):

<?php 
echo "yyy"
?>

I am working with xampp, I get response but it fades from page instantly. And again xxx is present inside p tag, does anyone know what is the reason why this happens. Thanks

  • 写回答

2条回答 默认 最新

  • weixin_33726313 2018-10-04 12:23
    关注

    It appears that when you click the button to get your response, it also refreshes the page in your browser. You can try the following to prevent this:

    <script>
    $("#register").click(function(evt) {
      evt.preventDefault()
    
      $.ajax({
        url:'registration.php',
        type: 'POST',
        success: function (response) {
          $("#result").html(response)
        }
      })
    })
    </script>
    

    This prevents your browser from doing what it normally does when you click a button.Any button inside <form>tags will automatically send a GET request within the current window, causing the page to refresh. The other alternative to preventDefault() is to use the attribute type="button" on your button and this will stop the button from being a type="submit" button.

    You can read more detailed information about the function I've used here:

    评论

报告相同问题?