开发者

ASP.NET / JavaScript - Ajax call, how to?

开发者 https://www.devze.com 2022-12-21 09:11 出处:网络
Please be gentle, as I\'m still new to web programming and -very- new to Ajax! I\'ve 开发者_JAVA百科created a C# function which extracts data from an mssql database, formats it to a json string and r

Please be gentle, as I'm still new to web programming and -very- new to Ajax!

I've 开发者_JAVA百科created a C# function which extracts data from an mssql database, formats it to a json string and returns that. Now I need to make a call from my javascript (jQuery) slider through an aspx page that is related to the C# code file.

I have actually never done anything like this before, from what I could tell by googling I need to use xmlHttpRequest, but how exactly do I make the function get hold of this string?

It would be awesome if someone had some example code that shows how this works.


The simplest way to do this is to convert your function into an ASHX file that writes the JSON to the HTTP response.

You can then call it using XmlHttpRequest, although you can call it much more easily using jQuery.

You can call it with jQuery like this:

$.get("/YourFile.ashx", function(obj) { ... }, "json");


It's relatively easy with jQuery if you mark the C# function as a [WebMethod] or make it part of a ASP.NET webservice. Both these techniques make it easy to have the response automatically converted into a JSON object by ASP.NET, which makes processing on the client easier (IMHO).

The example below is if the page has a WebMethod named GetData, but it's trivial to change the URL if you create a service.

$.ajax({ url: "somepage.aspx/GetData", 
         method: "POST", // post is safer, but could also be GET
         data: {}, // any data (as a JSON object) you want to pass to the method
         success: function() { alert('We did it!'); }
});

On the server:

[WebMethod]
public static object GetData() {
    // query the data...
    // return as an anonymous object, which ASP.NET converts to JSON
    return new { result = ... };
}
0

精彩评论

暂无评论...
验证码 换一张
取 消