0

我在 ASP.NET MVC 3 视图中有以下代码。出于某种原因,当我在 chrome 中运行它时,看看控制台它说:

未捕获的 ReferenceError:未定义 submitAjaxRequest

<script>
        $(function () {
            function submitAjaxRequest(eventId) {
                var request = $.ajax({
                    url: "/Toolbox/Blog/Delete",
                    type: "POST",
                    data: { id: eventId },
                    dataType: "json"
                });

            request.done(function (data, msg) {
                $('tr[data-id="' + eventId + '"').animate({
                    height:"0px"
                }).remove();
            });

            request.fail(function (data, msg) {
                $('#ajax-error').empty().toggle().append(msg).delay(1500).toggle();
            });
        }
    });
</script>
<table>
    <thead>
    <tr>
        <th>
            Title
        </th>
        <th>
            Content
        </th>
        <th>
            Time Stamp
        </th>
        <th style="width: 105px"></th>
    </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
    <tr data-id="@item.Id">
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Content)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TimeStamp)
        </td>
        <td>
            <a href="@Url.Action("Edit", "Blog", new { id=item.Id })"><img src="@Url.Content("~/Content/edit.png")" alt="Edit" /></a> | 
            <a href="@Url.Action("Details", "Blog", new { id=item.Id })"><img src="@Url.Content("~/Content/detail.png")" alt="Detail" /></a> |
            <img src="@Url.Content("~/Content/delete.png")" onclick="submitAjaxRequest('@item.Id')" width="48" />
        </td>
    </tr>
}
    </tbody>
</table>

为什么它不起作用?

4

1 回答 1

1

submitAjaxRequest是在另一个函数中定义的(document.ready在这种情况下是你的),那么它在全局 ( window) 范围内不可用,那么你onclick="submitAjaxRequest('@item.Id')"不知道这个函数。

尝试:

var submitAjaxRequest;

$(function () {
            submitAjaxRequest = function(eventId) {
                var request = $.ajax({
                    url: "/Toolbox/Blog/Delete",
                    type: "POST",
                    data: { id: eventId },
                    dataType: "json"
                });

            request.done(function (data, msg) {
                $('tr[data-id="' + eventId + '"').animate({
                    height:"0px"
                }).remove();
            });

            request.fail(function (data, msg) {
                $('#ajax-error').empty().toggle().append(msg).delay(1500).toggle();
            });
        }
    });
于 2013-07-15T13:25:25.700 回答