在我的ASP.net Web项目中,我在.js文件中编写了以下Javascript代码:

function getDeviceTypes() {
    var deviceTypes;
    $.ajax({
        async: false,
        type: "POST",
        url: "Controls/ModelSelectorWebMethods.aspx/getDeviceTypes",
        data: '{ }',
        contentType: "application/json;",
        dataType: "json",
        success: function(response) {
            deviceTypes = response.d;
        },
        error: function(xhr, status) {
            debugger;
            alert('Error getting device types.');
        }
    });    // end - $.ajax
    return deviceTypes;
}

直到我尝试将此.js文件加载到子目录中的页面中,效果一直很好。

假设我的项目名称为widget

当我在主虚拟目录中使用此代码时,Javascript将Controls/ModelSelectorWebMethods.aspx/getDeviceTypes解释为https://mysite.com/widget/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes,一切都很好。但是,在子目录中的页面上,Javascript将其解释为https://mysite.com/widget/subdirectory/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes,因此无法正常工作。

如何编写Javascript代码,以便可以从应用程序中任何目录的页面调用AJAX Web方法?

最佳答案

您有两种选择:

  • 用JavaScript构建配置/首选项对象,其中包含您所有环境特定的设置:
     var config = {
         base: <% /* however the hell you output stuff in ASPX */ %>,
         someOtherPref: 4
     };
    

    然后在AJAX网址前添加config.base(并在odt / test / Deployment服务器上更改config.base的值。)
  • 使用 <base /> HTML标记为所有相对URL设置URL前缀。这会影响所有相对URL:图像,链接等。

  • 就个人而言,我会选择选项1。您很可能会在其他位置找到该配置对象。

    显然,配置对象必须包含在您的评估服务器端代码的站点的一部分中。如果不配置服务器,则.js文件不会将其剪切。我总是将config对象包含在HTML <head>中;它是一个小的配置对象,其内容可以在每个页面上更改,因此最好将其粘贴在其中。

    10-04 22:24
    查看更多