简体   繁体   中英

Sitecore, jQuery ajax, and WebMethod returns the page itself

I am trying to use jQuery ajax to call a WebMethod on an aspx page that I have in my application. I am following this article: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

I noticed that when I try to make the ajax call, it is giving me the page itself (myPage.aspx) and not the results of my WebMethod. At this point, I am basically using the code straight from the article above. The javascript is:

$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
    $.ajax({
        type: "POST",
        url: "myPage.aspx/GetDate",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Replace the div's content with the page method's return.
            $("#Result").text(msg.d);
        }
    });
});
});

The myPage.aspx code-behind for the WebMethod is:

    [WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }

The strange thing is that I had it working on a separate test page, but when I tried to integrate it into the actual page where I want to use it, it doesn't. I couldn't find anything that resolved my issue when searching the site and web.

I'm running Sitecore 6.5 and .NET Framework version 4.0. Can anyone help or provide insight?

I am only familiar with PHP but usually you have to json_encode() your array before returning back. So for example in php

$TestArray['d'] = "All My HTML";
echo json_encode($TestArray);

//Then in Jquery

$("#Result").html(msg.d);

and make sure there is a div with the id of Result...

Typically, that happens when the request is either not a POST or doesn't have the application/json Content-Type set.

I'm not familiar with Sitecore, but others seem to have had trouble with it interfering with page methods: How to use jquery ajax and webmethod with sitecore

I think the problem is that Sitecore's URL rewriter will handle the request and ignore the /GetDate part of your url.

Therefore you must add your aspx to the <setting name="IgnoreUrlPrefixes" /> setting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM