Home > Web Front-end > JS Tutorial > body text

jQuery asp.net returns custom objects in json format_jquery

WBOY
Release: 2016-05-16 18:30:11
Original
942 people have browsed it

The client uses an html page to call an ashx file (general http handler) and returns a custom object in json format:
html:

Copy code The code is as follows:



< head>
ajax test
< ;!-The jQuery framework is referenced here->



Name: type="text" />Age:
type="text" />



handler.ashx file:
Copy code The code is as follows:

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Collections;
using System.Runtime.Serialization;
public class Handler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string name = context.Request.Params["name"].ToString();
string age = context.Request.Params ["age"].ToString();
person p1 = new person(name,age);
DataContractJsonSerializer djson = new DataContractJsonSerializer(p1.GetType());//Serialize the object into JavaScript object representation Method (JSON)
djson.WriteObject(context.Response.OutputStream, p1);
}
public bool IsReusable {
get {
return false;
}
}
[DataContract]//To serialize, be sure to add this attribute
public class person
{
[DataMember]//The attribute "DataMember" is only in the "property, indexer, field" declaration efficient.
public string Name="无名士";
[DataMember]
public string Age="0";
public override string ToString()
{
return "Name:" Name "Age:" Age;
}
public person(string name,string age)//Custom class person
{
this.Name = name;
this.Age = age ;
}
public person()
{ }
}
}
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