This article mainly introduces how JQuery submits data to the server in JSON format. If you need it, you can refer to JQuery to encapsulate Ajax data requests so that this operation is much easier to implement. 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
The 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.
The 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 description for RequestData
///
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 (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.