onClick请求会覆盖Ajax请求

时间:2015-02-20 14:12:03

标签: javascript jquery ajax asp.net-mvc-4 pagedlist

我正在关注Building Applications with ASP.NET MVC 4教程。但对我来说,ajax请求/?page=2&searchTerm=Res2被另一个直接的非Ajax请求/?page=2覆盖,该请求实际上是页面链接的href。这样就可以用新数据替换整个页面。

虽然教程顺利进行,但click只向服务器发送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 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关于相同的分页教程但是没有解决这个问题。

1 个答案:

答案 0 :(得分:1)

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

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

    // rest of your code...
}

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

    // rest of your code...
}