JQuery submits data in JSON format to the Server Sample Code

Source: Internet
Author: User

JQuery encapsulates Ajax data requests, making this operation much easier. In the past, we had to write a lot of code to implement this function. Now we only need to call the $. ajax () method and specify the request method, address, data type, and callback method. The code below demonstrates how to encapsulate the form data on the client into JSON format, send the data to the server through JQuery Ajax requests, and finally store the data in the database. The server is defined as a. ashx file. In fact, you can define the server as any type that can receive and process client data, such as Web Service, ASP. NET Page, and Handler.

First, the page form data is encapsulated into JSON format through JavaScript scripts on the client. The GetJsonData () function completes this function. Then, we use the $. ajax () method to send the data to the server's RequestData. ashx. Here the JSON. stringify () method is used, it can convert the data sent by the client to a JSON object, detailed content can be viewed here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Copy codeThe Code is as follows:
$ ("# BtnSend"). click (function (){
$ ("# Request-process-patent" pai.html ("submitting data. Do not close the current window ...");
$. Ajax ({
Type: "POST ",
Url: "RequestData. ashx ",
ContentType: "application/json; charset = UTF-8 ",
Data: JSON. stringify (GetJsonData ()),
DataType: "json ",
Success: function (message ){
If (message> 0 ){
Alert ("request submitted! We will contact you as soon as possible ");
}
},
Error: function (message ){
$ ("# Request-process-patent" failed .html ("failed to submit data! ");
}
});
});

Function GetJsonData (){
Var json = {
"Classid": 2,
"Name": $ ("# tb_name"). val (),
"Zlclass": "Test Type 1, test Type 2, test Type 3 ",
"Pname": $ ("# tb_contact_people"). val (),
"Tel": $ ("# tb_contact_phone"). val ()
};
Return json;
}

Let's take a look at the server code, RequestData. ashx.
Copy codeThe Code is as follows:
[Serializable]
Public class RequestDataJSON
{
Public int classid {get; set ;}
Public string name {get; set ;}
Public string zlclass {get; set ;}
Public string pname {get; set ;}
Public string tel {get; set ;}
}

/// <Summary>
/// Summary description for RequestData
/// </Summary>
Public class RequestData: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
Int num = 0;
Context. Response. ContentType = "application/json ";
Var data = context. Request;
Var sr = new StreamReader (data. InputStream );
Var stream = sr. ReadToEnd ();
Var javaScriptSerializer = new JavaScriptSerializer ();
Var PostedData = javaScriptSerializer. Deserialize <RequestDataJSON> (stream );

Tb_query obj = new tb_query ();
Obj. classid = PostedData. classid;
Obj. name = PostedData. name;
Obj. zlclass = PostedData. zlclass;
Obj. pname = PostedData. pname;
Obj. tel = PostedData. tel;
Obj. ip = context. Request. UserHostAddress. ToString ();
Obj. posttime = DateTime. Now. ToString ();

Try
{
Using (var ctx = new dbEntities ())
{
Ctx. tb_query.AddObject (obj );
Num = ctx. SaveChanges ();
}
}
Catch (Exception msg)
{
Context. Response. Write (msg. Message );
}

Context. Response. ContentType = "text/plain ";
Context. Response. Write (num );
}

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

Define a class RequestDataJSON with the Serializable feature attribute to deserialize the client data, so as to obtain the data and store it in the database. EntityFramework is used in the above Code to make the interactive code of the database very concise. There are two types of returned results, which correspond to the callback functions success () and error () in ajax (). In the success () callback function, if the returned result is greater than 0, it indicates the number of records added to the database through EntityFramework. In the error () callback function, the returned results show the details of the failure.

The RequestData class inherits the IHttpHandler interface, indicating that it processes client requests synchronously. Of course, you can also inherit the IHttpAsyncHandler interface to process asynchronous requests. The Code interface is similar.

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.