Ajax 请求被 onClick 请求覆盖

Ajax request is overriden by onClick request

我正在学习 Building Applications with ASP.NET MVC 4 教程。但对我来说 ajax 请求 /?page=2&searchTerm=Res2 被另一个直接的非 ajax 请求 /?page=2 覆盖,它实际上是页面 link 的 href。因此,这会用新数据替换整个页面。

虽然教程进行得很顺利,但点击只向服务器发送了一个 Ajax 请求。

$(function () {
    var ajaxSubmit = function () {
        var $form = $(this);

        var options = {
            url: $form.attr("action"),
            type: $form.attr("method"),
            data: $form.serialize()
        }

        $.ajax(options).done(function (data) {
            var $target = $($form.attr("data-otf-target"));
            var $effectHtml = $(data);

            $target.replaceWith($effectHtml);
            $effectHtml.effect("highlight");
        });

        return false;
    }

    var submitAutoCompleteForm = function (event, ui) {
        var $input = $(this);
        $input.val(ui.item.label);

        $input.parents("form:first").submit();
    }

    var createAutoComplete = function () {
        var $input = $(this);

        var options = {
            source: $input.attr("data-otf-autocomplete"),
            select: submitAutoCompleteForm
        }

        $input.autocomplete(options);
    }

    var getPage = function () {
        var $a = $(this);
        $a.attr("disabled", true);

        var options = {
            url: $a.attr("href"),
            data: $("form").serialize(),
            type: "get"
        }

        $.ajax(options).done(function (data) {
            var target = $a.parents("div.pagedList").attr("data-otf-target");
            $(target).replaceWith(data);
        });
    }

    $("form[data-otf-ajax='true']").submit(ajaxSubmit);
    $("input[data-otf-autocomplete]").each(createAutoComplete);
    $(".body-content").on("click", ".pagedList a", getPage);
})

Div 结果

<div id="restaurantList">
    <div class="pagedList" data-otf-target="#restaurantList">
        @Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.MinimalWithItemCountText)
    </div>

    @foreach (var item in Model)
    {
        <div>
            <h4>@item.Name</h4>
            <div>@item.City, @item.Country</div>
            <div>@item.CountOfReviews</div>
            <hr />
        </div>
    }
</div>

和布局

<div class="container body-content">
    @RenderBody()
</div>

我发现 this question 关于相同的分页教程,但这并没有解决这个问题。

因为您正在使用 AJAX 在提交表单和单击 a 时检索数据,所以您需要使用 preventDefault() 来阻止这些事件的默认操作。试试这个:

var ajaxSubmit = function (e) {
    e.preventDefault();

    // rest of your code...
}

var getPage = function (e) {
    e.preventDefault();

    // rest of your code...
}