Jquery Ajax JSON

Source: Internet
Author: User

Serialization character method: Pay attention to the reference"System. runtime. serializationAndSystem. servicemodel. Web"
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. runtime. serialization. JSON;
Using system. servicemodel. Web; // remember to reference this namespace
Using system. IO;
Using system. text;

Namespace BLL
{
/// <Summary>
/// Serialize the object class
/// </Summary>
Public class jsonhelper
{
Public jsonhelper ()
{
//
// Todo: Add constructor logic here
//
}

/// <Summary>
/// Serialize the object to a JSON string
/// </Summary>
/// <Typeparam name = "T"> Object Type </typeparam>
/// <Param name = "OBJ"> Object object </param>
/// <Returns> JSON string </returns>
Public static string getjson <t> (t obj)
{
// Remember to add reference system. servicemodel. Web
/**
* If the above reference is not added, system. runtime. serialization. JSON; JSON is supplied.
**/
Datacontractjsonserializer JSON = new datacontractjsonserializer (typeof (t ));
Using (memorystream MS = new memorystream ())
{
JSON. writeobject (MS, OBJ );
String szjson = encoding. utf8.getstring (Ms. toarray ());
Return szjson;
}
}

/// <Summary>
/// Restore the JSON string to an object
/// </Summary>
/// <Typeparam name = "T"> Object Type </typeparam>
/// <Param name = "szjson"> JSON string </param>
/// <Returns> Object entity </returns>
Public static t parseformjson <t> (string szjson)
{
T OBJ = activator. createinstance <t> ();
Using (memorystream MS = new memorystream (encoding. utf8.getbytes (szjson )))
{
Datacontractjsonserializer DCJ = new datacontractjsonserializer (typeof (t ));
Return (t) DCJ. readobject (MS );
}
}
}
}

Entity class:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;

Namespace Model
{
Public class jsonitem
{
Public String username {Get; set ;}

Public String PWD {Get; set ;}
}
}

Call Method: In reflection mode, you only need to pass the method to execute
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. Web. Services;
Using system. text;

Namespace test. jquery. JSON
{
/// <Summary>
/// $ Codebehindclassname $ abstract description
/// </Summary>
[WebService (namespace = "http://tempuri.org/")]
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
Public class JSON: ihttphandler
{

Public void processrequest (httpcontext context)
{
Context. response. contenttype = "text/plain ";
// Reflection mechanism: you only need to pass in the method to execute the method and obtain data ..
If (context. request ["cmd"]! = NULL)
{
String cmd = context. request ["cmd"];
VaR method = This. GetType (). getmethod (CMD );
If (method! = NULL)
{
Method. Invoke (this, new object [] {context });
}
}
}

/// <Summary>
/// Serialized JSON string
/// </Summary>
Public void getinfo (httpcontext context)
{
Model. jsonitem item = new model. jsonitem ();
Model. jsonitem Item1 = new model. jsonitem ();
List <model. jsonitem> List = new list <model. jsonitem> ();
Item. Username = "aaaa ";
Item. Pwd = "1111 ";
List. Add (item );
Item1.username = "BBBB ";
Item1.pwd = "2222 ";
List. Add (Item1 );
String strjson = BLL. jsonhelper. getjson <list <model. jsonitem> (list );
Context. response. Write (strjson );
}

/// <Summary>
/// Serialized JSON string
/// </Summary>
Public void getinfo1 (httpcontext context)
{
Model. jsonitem item = new model. jsonitem ();
Model. jsonitem Item1 = new model. jsonitem ();
List <model. jsonitem> List = new list <model. jsonitem> ();
Item. Username = "ABC ";
Item. Pwd = "123 ";
List. Add (item );
Item1.username = "BCD ";
Item1.pwd = "234 ";
List. Add (Item1 );
String strjson = BLL. jsonhelper. getjson <list <model. jsonitem> (list );
Context. response. Write (strjson );

// String output = string. Format ("'username': '{0}', 'pwd': '{1}'", "CCCC", "3333 ");
// String output1 = string. Format ("'username': '{0}', 'pwd': '{1}'", "dddd", "4444 ");
// Stringbuilder result = new stringbuilder ();
// Result. appendformat ("[{0} {1} {2}, {3} {4} {5}]", "{", output ,"}","{", output1 ,"}");
// Context. response. Write (result. tostring ());
// Context. response. End ();
}

Public bool isreusable
{
Get
{
Return false;
}
}
}
}

HTML code call:
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>

<SCRIPT src = "http://imwujianhao.blog.163.com/blog/../jquery-1.4.2.js" type = "text/JavaScript"> </SCRIPT>

<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Function btnclick (){
VaR uid = $ ("# text1"). Val ();
VaR Pwd = $ ("# text2"). Val ();
$. Ajax ({
URL: "JSON. ashx ",
Type: "Post ",
Data: {cmd: "getinfo", password: Pwd },
Beforesend: Loading,
Success: function (data ){
VaR JSON = eval (data); // eval ("(" + Data + ")");
$ ("# Dd"). Empty (); // clear dd Information
$. Each (JSON, function (idx, item ){
VaR user = item. Username;
VaR pass = item. pwd;
$ ("# Dd"). append ("<B> Username:" + User + "Password:" + pass + "</B> ");
});
}

});
}
Function loading (){
$ ("# Dd" ).html (" ");
}
Function btnclick1 (){
$. Ajax ({
URL: "JSON. ashx ",
Type: "Post ",
Data: {cmd: "getinfo1 "},
Beforesend: Loading,
Success: function (data ){
// Use the eval function
VaR JSON = eval (data );
$ ("# Dd"). Empty ();
// Because the above is a list set
For (VAR I = 0; I <JSON. length; I ++ ){
$ ("# Dd "). append ("// Alert (JSON [I]. ID + "name:" + JSON [I]. Name );
}
}

});
}
</SCRIPT>

</Head>
<Body>
<Div>
<Input type = "text" name = "text1" id = "text1"/> <br/>
<Input type = "text" name = "text2" id = "text2"/>
<Br/>
<Input type = "button" id = "btn1" value = "Event 1" onclick = "btnclick ()"/>
<Input type = "button" id = "button1" value = "Event 2" onclick = "btnclick1 ()"/>
</Div>
<Div id = "DD">
SD
</Div>
</Body>
</Html>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.