簡體   English   中英

JavaScript無法在單獨的文件中工作

[英]JavaScript not working from separate file

我正在嘗試將JS移到單獨的文件中,而不是直接將其放在頁面上。 但是,由於某種原因,我無法使其正常運行。

我想根據下拉菜單選擇更新站點。 我現在的操作方式是:

視圖:

<script type="text/javascript">
$(document).ready(function () {
    $("#EntityType").change(function () {
        /* Get the selected value of dropdownlist */
        var selectedID = $(this).val();

        /* Request the partial view with .get request. */
        $.get('/Entity/Create_DropDownList/' + selectedID, function (data) {

            /* data is the pure html returned from action method, load it to your page */
            $('#entity_form_attributes').html(data);
            /* little fade in effect */
            $('#entity_form_attributes').fadeIn('fast');
        });
    });
});
</script>

    <div class="editor-field">
        @Html.DropDownList("EntityType", (SelectList)ViewData["Types"])
    </div>

    <div id="entity_form_attributes"></div>

可以了 局部視圖應按原樣加載到div標簽中。 但是,如果創建一個JavaScript文件,然后將腳本移入該文件,它將失敗。 在共享的起始站點中,我包含了JavaScript文件。

誰能看到我在做什么錯。 該應用程序是MVC3應用程序。 我需要設置某種設置/屬性才能使其正常工作嗎?

誰能看到我做錯了什么。

是的,您已經在此處對網址進行了硬編碼,而不是使用Url幫助程序來生成它。 您絕對不應這樣做:

$.get('/Entity/Create_DropDownList/'

當您在IIS中部署應用程序時,這會中斷,因為您的URL錯誤。 由於使用此硬編碼的url,因此您省略了在開頭包含虛擬目錄名稱的操作。

因此,在ASP.NET MVC應用程序中處理URL時,請始終使用Url幫助器。 因此,根據您的情況,您可以在視圖中將此URL生成為HTML5 data-*屬性:

@Html.DropDownList(
    "EntityType", 
    (SelectList)ViewData["Types"], 
    new { data_url = Url.Action("Create_DropDownList", "Entity") }
)

然后在單獨的javascript文件中只需檢索以下網址並使用它即可:

$("#EntityType").change(function () {
    /* Get the selected value of dropdownlist */
    var selectedID = $(this).val();

    /* Get the url from the data-url HTML attribute */ 
    var url = $(this).data('url');

    /* Request the partial view with .get request. */
    $.get(url, { id: selectedID }, function (data) {
        /* data is the pure html returned from action method, load it to your page */
        $('#entity_form_attributes').html(data);
        /* little fade in effect */
        $('#entity_form_attributes').fadeIn('fast');
    });
});

暫無
暫無

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

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