问题
I'm running Sitecore 6.4 and trying to get some data using ajax and webmethod in Sitecore. Everything is in a sublayout (user control)
This is the code that calls the webmethod:
$("#NextBanner").click(function () {
$.ajax({
type: "POST",
url: "/GetNext",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (err) {
alert('error');
}
});
This is the webmethod, returns a string:
[WebMethod]
public static string GetNext()
{
return "Hello";
}
In a test project without using Sitecore I used "Default.aspx/GetNext" as the url for the ajax call but now obviously this doesn't work, I get 404 not found error because of the url.
What should the url be? The sublayout path is: /layouts/sublayouts/test.ascx
Any recommendation on a different approach of achieving this?
Thanks, T
Update
Thanks everybody for the answers.
I ended up creating a web service under website/sitecore/shell/webservices, not sure if that's the right place to put the web service, any suggestions?
Thanks, T
回答1:
Put the code in a WebForm. You can't call a sublayout like a page. Reference the file by its file system path in your ajax call, e.g. /layouts/ajaxProcessor.aspx
You should also check out the following blog post about sitecore and ajax goodness: http://blog.velir.com/index.php/2011/09/22/lazy-websites/
回答2:
Instead of using web methods, we'll typically make use of ASP.NET MVC controllers to serve JSON data in Sitecore projects. Properly setup, you can access some Sitecore.Context values (just not Item) and all Sitecore data access APIs.
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/10/Sitecore-MVC-Crash-Course.aspx
http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/
The Json() ActionResult option in MVC controllers makes sending back serialized data really easy.
回答3:
I created a folder under 'Website' and placed my web services there.
来源:https://stackoverflow.com/questions/7560111/how-to-use-jquery-ajax-and-webmethod-with-sitecore