Page Method calls from jQuery to Sharepoint

2019-04-10 11:23发布

问题:

I have an application page (aspx) deployed in the _LAYOUTS folder of MS SharePoint 2010.

I would like to call a method inside that page marked with the [WebMethod] attribute using jQuery. I am using the following code on document.ready():

$("#btnOk").click(function () {
    var theUrl = '/_layouts/MyProject/MyPage.aspx/MyMethod';
    $.ajax({
        type: "get",
        dataType: "json",
        url: theUrl,
        data: {},
        success: function (response) {
            [...]
        },
        error: function (xhr, textStatus, errorThrown) {
            [...]
        }
    });
});

This code unfortunately does not work. The problem is with the URL: in fact it works if I use an absolute URL like this

var theUrl = 'http://server/sites/xxx/_layouts/MyProject/MyPage.aspx/MyMethod';

How can I transform my path in an absolute one?

回答1:

/_layouts/MyProject/MyPage.aspx/MyMethod

in your example is equivalent to:

http://server/_layouts/MyProject/MyPage.aspx/MyMethod

that is your problem. starting with / means start at the root. You should adjust this. If it has to be somehow dynamic because it can be used multiple places, you may need to use the codebehind to inject the path or something. If this is always run from a static place, just modify the url.

If the page you're running it from is, for instance:

http://server/sites/xxx/Somepage.aspx

Then just change it to

_layouts/MyProject/MyPage.aspx/MyMethod

with no slash.

If you are in a subfolder, for instance:

http://server/sites/xxx/Pages/Somepage.aspx

then you can do this:

../_layouts/MyProject/MyPage.aspx/MyMethod

the .. will take you up one folder.