Using jQuery to consume an ASP.NET Ashx from JSON in two files
Here is a basic asp.net based JSON based ‘webservice’ which can be implemented with two files and requires no compilation
Javascript code (DataHandler.js):
function CallHandler() { $.ajax({ url: "DataHandler.ashx", contentType: "application/json; charset=utf-8", dataType: "json", data: { 'page': '100AAAAAf00' }, responseType: "json", success: OnComplete, error: OnFail }); return false; } function OnComplete(result) { alert(JSON.stringify(result)); } function OnFail(result) { alert('Request Failed'); } CallHandler();
Server side code (DataHandler.ashx):
<%@ WebHandler Language="C#" %></pre> using System.Text; using System.Web; using System.Web.Script.Serialization; public class test { public string var1 {get;set;} public string var2 {get;set;} public string page {get;set;} public test() { var1 = "aaaa"; var2 = "bbb"; } } public class GetDataHandler : IHttpHandler { public HttpContext context; public HttpRequest request; public HttpResponse response; public void handleRequest() { //writeRaw("this is a message"); writeJson(new test() { page = request["page"] }); } public bool IsReusable { get { return false; } } public void ProcessRequest (HttpContext _context) { context = _context; request = _context.Request; response = _context.Response; context.Response.ContentType = "application/json"; context.Response.ContentEncoding = Encoding.UTF8; handleRequest(); } public void writeJson(object _object) { JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string jsondata = javaScriptSerializer.Serialize(_object); writeRaw(jsondata); } public void writeRaw(string text) { context.Response.Write(text); } }
result
{"var1":"aaaa","var2":"bbb","page":"100AAAAAf00"}
references
based on source code samples from:
Nicely done. Thanks a lot.
I had to add these two lines for the status for Firefox browser to display properly my response (I am using Visual Studio 2010 Entity Framework 4):
// Put the Header
Response.Status = “400 Bad Request”;
Response.StatusCode = 400;
This might help other people having the same issue.
Comment by Moise Ndala | March 28, 2012 |