【问题标题】:How to specify page url in jquery ajax call from Master Page in asp.net如何在 asp.net 中的母版页中指定 jquery ajax 调用中的页面 url
【发布时间】:2016-06-13 02:57:10
【问题描述】:

我试图在我的 asp.net 项目中从母版页调用 webmethod,几乎成功了。在我的解决方案资源管理器中,“母版页”和“MyService.asmx”位于根文件夹中,但内容页面位于文件夹中,比如说“Admin”文件夹。因此,当我转到“Admin/firstcontent.aspx”页面时,我必须像这样在母版页中指定 url

 $.ajax({
            type: "POST",
            url: "../MyService.asmx/HelloWorld",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.d);
            }
        });

但是当我进入“Admin/Master/secondcontent.aspx”页面时,我必须像这样指定网址

 $.ajax({
            type: "POST",
            url: "../../MyService.asmx/HelloWorld",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.d);
            }
        });

第二个问题:-在每个内容页面中,我必须在 head 部分调用 jquery.min。

【问题讨论】:

    标签: jquery asp.net ajax web-services master-pages


    【解决方案1】:

    我通常做的是在主页面中创建一个全局 javascript 变量,例如 window.applicationBaseUrl='<%= Url.Content("~/")' %>' 并在每个子页面中使用它,如下所示:

    $.ajax({
            type: "POST",
            url: window.applicationBaseUrl + "MyService.asmx/HelloWorld",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.d);
            }
        });
    

    将应用程序部署到 IIS 时,相对路径可能会出错。

    【讨论】:

    • 这里的网址是什么?
    • UrlHelper 类,在 System.Web.Mvc 中
    • 我没有使用 MVC
    • 然后尝试使用 Request.ApplicationPath
    【解决方案2】:

    首先你必须定义你的应用程序的根路径,比如

     var rootpath="www.yourdomainname.com" or "localhost:8080"
    

    在使用 rootpath 变量并调用你的方法之后

           $.ajax({
              type: "POST",
               url: rootpath + "MyService.asmx/HelloWorld",
              data: '{}',
                     contentType: "application/json; charset=utf-8",
              dataType: "json",
            success: function (response) {
            alert(response.d);
        }
    });
    

    试试这个。谢谢

    【讨论】:

      猜你喜欢
      • 2011-05-26
      • 1970-01-01
      • 2016-08-21
      • 2013-11-30
      • 2012-04-28
      • 1970-01-01
      • 2013-10-16
      • 2017-03-03
      • 1970-01-01
      相关资源
      最近更新 更多