简体   繁体   English

使用AJAX单击提交按钮后刷新div而不是页面

[英]Refreshing a div, rather than page after clicking submit button using AJAX

I have a table populated by a SQL database. 我有一个由SQL数据库填充的表。 The table is hidden until a search button is clicked to return the results. 该表将被隐藏,直到单击搜索按钮以返回结果。

I'm trying to use ajax to refresh the table, rather than the page. 我正在尝试使用ajax刷新表,而不是页面。 If the page refreshes, the class on the table returns making it hidden again so the content of the table only appears briefly. 如果页面刷新,表上的类将返回再次隐藏,因此表的内容只会短暂显示。

$(function () {
    $('#searchForm').on('submit', function () {
        $.ajax({
            type: 'GET',
            url: 'Index',
            data: $('#searchForm').serialize(),
            success: function () {
                $("#resultsTable").removeClass("d-none");
            }
        });
    });
});

Form: 形成:

<form asp-page="./Index" id="searchForm" method="get">
    <div class="form-actions no-color">
        <p>
            Find by name:
            <input type="text" name="SearchString" value="@Model.CurrentFilter" />
            <input type="submit" value="Search" class="btn btn-default" id="searchName" />

            @*<a asp-page="./Index">Back to full List</a>*@
        </p>
    </div>
</form>

The code above runs and executes fine but the page still refreshes. 上面的代码运行并执行正常,但页面仍然刷新。 I suspect I've missed something. 我怀疑我错过了什么。

use e.preventDefault() 使用e.preventDefault()

 $(function () {
        $('#searchForm').on('submit', function (e) {
    e.preventDefault()
            $.ajax({
                type: 'GET',
                url: 'Index',
                data: $('#searchForm').serialize(),
                success: function () {
                    $("#resultsTable").removeClass("d-none");
                }
            });
        });
    });

use event.preventDefault() 使用event.preventDefault()

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. Event接口的preventDefault()方法告诉用户代理,如果事件没有得到明确处理,则不应该像通常那样采取默认操作。 The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once. 事件继续像往常一样传播,除非其事件侦听器之一调用stopPropagation()或stopImmediatePropagation(),其中任何一个都会立即终止传播。

<input id="search" type="text" name="SearchString" value="@Model.CurrentFilter" />

$(function () {
$('#searchForm').on('submit', function (e) {
    e.preventDefault();
    const search = $('#search').val();
    $.ajax({
        type: 'GET',
        url: 'Index',
        data: { search },
        success: function () {
            $("#resultsTable").removeClass("d-none");
        }
    });
  });
});

Then in your PHP 然后在你的PHP中

<?php searchValue = $_GET['search']; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM