簡體   English   中英

將javascript移至單獨的文件,ajax調用出現錯誤

[英]Moved javascript to separate file, ajax calls are giving error

在嘗試清理我的代碼庫時,我將所有JavaScript從腳本標記移到了自己的JavaScript文件。 之后,我所有的ajax調用都失敗了。

這是JavaScript,這完全是* .cshtml文件中的樣子,不包括script標簽:

$(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頁面上時,是否還需要其他語法?

編輯:我正在將我的javascript文件加載到cshtml文件的最后,就在結束標記之前。

另外,我還收到404。 如果代碼保持不變,為什么現在會得到404?

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

該行需要在cshtml頁面上呈現。 它不會在.js文件中進行處理。

問題在於您設置ajax網址的方式

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

ASP.NET MVC標簽幫助程序@ Url.Action()在.js文件中不起作用。

您可以將URL放在隱藏的表單字段中,然后從那里讀取它。

最好將其放置在.cshtml中的任何形式之外的任何地方,這樣,由於任何原因它都不會以表單形式發回。

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

然后使用以下代碼設置jQuery ajax網址

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM