ASP.NETJavaScript - Ajax call, how to? - Stack Overflow

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

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

I've 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.

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

I've 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.

Share Improve this question asked Mar 1, 2010 at 14:52 cc0cc0 1,9508 gold badges40 silver badges58 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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 = ... };
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745329029a4622791.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信