Home > Web Front-end > JS Tutorial > Detailed explanation of how jQuery getJSON processes data code in json

Detailed explanation of how jQuery getJSON processes data code in json

巴扎黑
Release: 2017-07-03 09:33:37
Original
1243 people have browsed it

Ashx handler: If you need to return an object in json format, you need to set the mime type to: "application/json".

Html code:

The code is as follows:

<script type="text/javascript" src="/js/jquery-1.4.js"></script> 
<script type="text/javascript"> 
function jsonTest1() 
{ 
$.ajax({ 
url:"Handler.ashx", 
data:{"type":"ajax"}, 
datatype:"json", 
type:"get", 
success:function(data) 
{ 
document.getElementById(&#39;p1&#39;).innerHTML=data;//因为mime类型是文本 所以返回回来的是json格式的字符串 
} 
}); 
} 
function jsonTest2() 
{ 
$.getJSON( 
&#39;Handler.ashx&#39;, 
{&#39;type&#39;: &#39;json&#39;,&#39;name&#39;:&#39;qixuejia&#39; }, //类型格式 
function(data) 
{ 
for(var i=0;i<data.length;i++) 
{ 
alert(data[i]["UserId"]) 
} 
} 
); 
} 
</script> 
<form id="form1" runat="server"> 
<p id="p1"> 
</p> 
<input type="button" value="jQuery.ajax()" onclick="jsonTest1()"/> 
<input type="button" value="jQuery.getJSON()" onclick="jsonTest2()"/> 
</form>
Copy after login

Ashx handler: If you need to return an object in json format, you need to set the mime type to: "application/ json".
Looking at the jQuery source file, you can see that getJSON is implemented like this:
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},

The code is as follows:

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<UserInfo> listUser = UserInfoManage.GetUserInfoBySQL("Select Top 5 * From Userinfo"); 
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter(); 
timeConverter.DateTimeFormat = "yyyy&#39;-&#39;MM&#39;-&#39;dd&#39; &#39;HH&#39;:&#39;mm&#39;:&#39;ss"; 
string
 ResJsonStr = JsonConvert.Serialize
Object
(listUser, timeConverter); 
context.Response.Write(ResJsonStr); 
}
Copy after login


The above is the detailed content of Detailed explanation of how jQuery getJSON processes data code in json. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template