最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 = ... };
}
发布评论

评论列表(0)

  1. 暂无评论