PHP响应逐渐消失

时间:2018-10-04 12:16:01

标签: php ajax xampp

我试图通过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标签中,有人知道这是什么原因吗? 谢谢

2 个答案:

答案 0 :(得分:5)

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

$embedded->Object

这可防止您的浏览器执行单击按钮时的正常操作。<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"按钮。

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

答案 1 :(得分:-1)

只是在提交前阻止页面。

<input type='submit' id='register'>
<div id='result'></div>
$("#register").click(function(e){
 e.preventDefault();
 $.ajax({
  url:'registration.php',
  type: 'GET',
  success:function(response){
   document.getElementById("result").innerHTML = response;
  }
 })
});
相关问题