【问题标题】:A cannot refresh the page through jquery while sending ajaxA 发送ajax时无法通过jquery刷新页面
【发布时间】:2018-04-18 08:19:58
【问题描述】:

下面是我的html代码,我想知道两者之间是否有区别 a 和按钮;当我按下 a 时,我可以看到它确实发布了请求,但是 页面仍然存在,没有任何变化。但是按钮会发出请求并刷新页面。另一个奇怪的事情是我评论的内容可以正常工作。

  <html>
    <button onclick="nextPage()">test</button>
    <a onclick="nextPage()">test</a>
    <script>
        function nextPage() {
        $.ajax({
            type: 'post',
            url: $('#searchform').attr('action'),
            data: {lastRow: $("input[name='lastRow']").val()}
        });
        /*$("input[name='startRow']").val('');
        $('#searchform').submit();*/
        return false;
        }
    </script>
    </html>

那么任何人都可以说出这背后的技巧吗?感谢您的宝贵时间。

【问题讨论】:

  • 这取决于您的按钮是否有 type=submit。如果是,它将刷新页面

标签: jquery ajax button


【解决方案1】:

A 标签有默认功能,而button 没有。 https://api.jquery.com/event.preventdefault/

添加 e.PreventDefault()

 <script>
    function nextPage(e) {
    e.PreventDefault();
    $.ajax({
        type: 'post',
        url: $('#searchform').attr('action'),
        data: {lastRow: $("input[name='lastRow']").val()}
    });
    /*$("input[name='startRow']").val('');
    $('#searchform').submit();*/
    return false;
    }
</script>

【讨论】:

  • 如果nextPage 事件是通过jquery $("button,a").click(nextPage); 连接起来的,但它在onclick= 上,所以e 中的e 不是jquery 事件。class="comcopy">跨度>
【解决方案2】:

preventDefault()方法如果可以取消则取消该事件,这意味着属于该事件的默认动作不会发生。

例如,这在以下情况下很有用:

  • 点击“提交”按钮,阻止其提交表单
  • 点击链接,阻止链接跟随网址

所以你可以重写你的代码,如下所示。

<html>
    <button onclick="nextPage($event)">test</button>
    <a onclick="nextPage($event)">test</a>
    <script>
        function nextPage(event) {
        event.preventDefault();
        $.ajax({
            type: 'post',
            url: $('#searchform').attr('action'),
            data: {lastRow: $("input[name='lastRow']").val()}
        });
        /*$("input[name='startRow']").val('');
        $('#searchform').submit();*/
        return false;
        }
    </script>
    </html>

【讨论】:

  • 我猜默认操作在这种情况下不相关,顺便说一句,我在控制台'$event is not defined'中遇到错误
【解决方案3】:

按钮的默认typesubmit

What is the default button type?

所以你的按钮没有类型:

<button onclick="nextPage()">test</button>

运行nextPage() ajax 函数,但随后也会提交表单 - 为您提供“页面刷新”。

将类型指定为按钮以阻止其自动提交表单/页面

<button type='button' onclick="nextPage()">test</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2013-08-10
    • 2023-04-03
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多