Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么下面的jQueryAjax调用只执行一次?_Jquery_Ajax_Asp.net Mvc - Fatal编程技术网

为什么下面的jQueryAjax调用只执行一次?

为什么下面的jQueryAjax调用只执行一次?,jquery,ajax,asp.net-mvc,Jquery,Ajax,Asp.net Mvc,我的ASP.NET MVC项目中有以下脚本: $(function () { var ajaxFormSubmit = function () { var $form = $(this); var options = { url: $form.attr("action"), type: $form.attr("method"), data: $form.serialize() }; $.ajax(options

我的ASP.NET MVC项目中有以下脚本:

$(function () {

var ajaxFormSubmit = 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 $newHtml = $(data);
        $target.replaceWith($newHtml);
    });

    return false;
};

$("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});
为什么这个函数只执行一次?此函数用于更新对象列表,以下是razor视图上的表单:

<form  method="get" action="@Url.Action("Index")" data-otf-ajax ="true" 
data-otf-target="#RestaurantList">
<input type="search" name="searchTerm" />
<input type="submit" value="Search By Name" />
</form>

<div id="RestaurantList">
@Html.Partial("_Restaurants")
</div>

@Html.Partial(“\u餐厅”)

您的函数不会只执行一次。问题在于,当第一次执行处理程序时,您将用ajax调用返回的HTML代码替换id为
RestaurantList
的元素

所以,下次执行时,这一行

var $target = $($form.attr("data-otf-target"));
不会有预期的行为(因为您的文档中不再有id为
RestaurantList
的元素)

尝试使用.html()方法而不是replaceWith()更新
RestaurantList
元素的内容:


这样,您的元素仍然具有相同的id。处理程序的下一次执行应该可以正常工作。

将javascript代码放在
RestaurantList
div之外……可能它会被ajax调用覆盖。尝试使用输入类型
按钮
并使用Jquery的
单击(函数)执行上述函数
请务必让我知道..javascript代码在单独的文件中,我将其与jquery脚本(@scripts.Render..)捆绑在一起。当我在函数中添加警报时,每次提交时都会显示结果,但视图中的更新只会在第一次完成
$.ajax(options).done(function (data) {
        var $target = $($form.attr("data-otf-target"));
        var $newHtml = $(data);
        $target.html($newHtml);
    });