Ajax请求被onClick请求覆盖

Ajax request is overriden by onClick request

本文关键字:请求 覆盖 onClick Ajax      更新时间:2024-03-04

我正在学习使用ASP.NET MVC 4构建应用程序教程。但对我来说,ajax请求/?page=2&searchTerm=Res2被另一个直接的非ajax请求/?page=2覆盖,后者实际上是页面链接的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 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>

我在相同的分页教程中发现了这个问题,但这并不能解决这个问题。

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

var ajaxSubmit = function (e) {
    e.preventDefault();
    // rest of your code...
}
var getPage = function (e) {
    e.preventDefault();
    // rest of your code...
}