JavaScript 无法从单独的文件工作

JavaScript not working from separate file

本文关键字:文件 工作 单独 JavaScript      更新时间:2023-09-26

我正在尝试将我的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 进行了硬编码,而不是使用 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 文件中,只需检索此 URL 并使用它:

$("#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');
    });
});