7*4 2019-08-13 16:08 采纳率: 50%
浏览 51

如何停止页面重新加载

This question already has an answer here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/45634088/how-to-prevent-page-from-reloading-after-form-submit-jquery" dir="ltr">How to prevent page from reloading after form submit - JQuery</a>
                            <span class="question-originals-answer-count">
                                (1 answer)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2019-08-13 16:58:29Z" class="relativetime">9 months ago</span>.</div>
        </div>
    </aside>

I'm trying to use ajax jquery to stop my page from reloading whenever the button is pressed, but the page is still reloading after I implemented it.

This is just a test system for "liking" a post.

//foreach loop that echos out row

foreach($dbData as $post){
  <p id="likecount" class = "likecount"> </p>
     <p>
     <form method="post" id="liketest" class="redirect" >
     <button type="submit" id="like" name="like" value= "'.$post["id"].'">
         <i class="fa fa-heart"></i>
     </button>
     </form>
     </p>
}

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#like').focus();
            $('#like').keypress(function(event) {
                var key = (event.keyCode ? event.keyCode : event.which);
                if (key == 13) {
                    var info = $('#like').val();
                    $.ajax({
                        method: "POST",
                        url: "index.php",
                        data: {like: info},
                        success: function(status) {
                            $('#likecount').append(status);
                            $('#like').val('');
                        }
                    });
                };
            });
        });
    </script>
<?php
if (isset($_POST['like'])) {
    echo '<h1>'.$_POST['like'];
}
?>

I expect it to not reload the page but the actual output is the page still reloading once the button is clicked.

</div>
  • 写回答

4条回答 默认 最新

  • weixin_33735077 2019-08-13 16:12
    关注

    You can use:

    event.preventDefault()

    after

    $('#like').keypress(function(event) {

    to stop reloading the page.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号