将javascript移动到单独的文件中,ajax调用会出现错误

Moved javascript to separate file, ajax calls are giving error

本文关键字:调用 ajax 错误 移动 javascript 单独 文件      更新时间:2024-01-16

在清理代码库时,我将所有javascript从脚本标记移到了它们自己的javascript文件中。之后,我所有的ajax调用都失败了。

这是javascript,这就是*.cshtml文件中的确切情况,不包括脚本标记:

$(function () {
    $("#weightList").change(function () {
        var weight = $("#weightList").val();
        var conference = $("#conference").val();
        $("#wrestlerAList").prop('disabled', true);
        $("#wrestlerBList").prop('disabled', true);
        $.ajax({
            url: '@Url.Action("GetByWeight", "Wrestler")',
            data: {
                weight: weight
            },
            type: 'POST',
            success: function (data) {
                var wrestlers = "<option></option>";
                $.each(data, function (i, wrestler) {
                    wrestlers += "<option value='" + wrestler.Value + "'>" + wrestler.Text + "</option>";
                });
                $("#wrestlerAList").html(wrestlers);
                $("#wrestlerBList").html(wrestlers);
                $("#wrestlerAList").prop('disabled', false);
                $("#wrestlerBList").prop('disabled', false);
            },
            error: function (error) {
                alert("An error occurred retrieving the wrestlers for this weight.");
            }
        });
    });
});

我试过删除"$(function(){…});",但没有成功。当javascript不直接在cshtml页面上时,是否需要其他语法?

编辑:我正在cshtml文件的最后加载javascript文件,就在结束标记之前。

另外,我要回404。如果代码保持不变,为什么现在会得到404?

 url: '@Url.Action("GetByWeight", "Wrestler")',

这一行需要在cshtml页面上呈现。它不会在.js文件中处理。

问题在于设置ajax url 的方式

url: '@Url.Action("GetByWeight", "Wrestler")'

ASP。NET MVC标记帮助程序@Url。Action()在.js文件中不起作用。

你可以将url放在一个隐藏的表单字段中,然后从那里读取。

将它放在.cshtml中的某个位置,最好放在任何表单之外,这样它就不会因为任何原因而返回到表单中。

@Html.Hidden("ServiceUrl", Url.Action("GetByWeight", "Wrestler"))

然后使用下面的代码设置jQuery ajax url

url: $('#ServiceUrl').val(),