html代码:
<script type="text/javascript" src="/js/<a%20style=" color: text-decoration:underline title="jquery" href="https://www.php.cn/zt/15736.html" target="_blank">jquery-1.4.js"></script>
<script type="text/javascript"> <br>function jsonTest1() <br>{ <br>$.ajax({ <br>url:"Handler.ashx", <br>data:{"type":"ajax"}, <br>datatype:"json", <br>type:"get", <br>success:function(data) <br>{ <br>document.getElementById('div1').innerHTML=data;//因为mime类型是文本 所以返回回来的是json格式的字符串 <br>} <br>}); <br>} <br>function jsonTest2() <br>{ <br>$.getJSON( <br>'Handler.ashx', <br>{'type': 'json','name':'qixuejia' }, //类型格式 <br>function(data) <br>{ <br>for(var i=0;i<data.length;i++) <br>{ <br>alert(data[i]["UserId"]) <br>} <br>} <br>); <br>} <br></script>
Ashx处理程序:如果需要返回json格式的对象,需要把mime类型设置为:"application/json"。
查看jQuery源文件,可以看出getJSON这样实现的:
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
public void ProcessRequest(HttpContext context)
{
if (context.Request.Params["type"].Equals("ajax"))
{
context.Response.ContentType = "text/plain";
}
else
{
context.Response.ContentType = "application/json";
}
GetInfo(context);
}
public bool IsReusable
{
get
{
return false;
}
}
public void GetInfo(HttpContext context)
{
System.Collections.Generic.List
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
string ResJsonStr = JsonConvert.SerializeObject(listUser, timeConverter);
context.Response.Write(ResJsonStr);
}










