jquery submits data to server-side sample code in JSON _jquery

Source: Internet
Author: User
jquery encapsulates Ajax data requests, making the operation much easier to implement. We used to write a lot of code to implement this function, and now we just need to call the $.ajax () method and indicate the way, address, data type, and callback method of the request. The following code shows how to encapsulate client form data in JSON format and then send the data to the server via a jquery Ajax request and eventually store the data in the database. The service side 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,handler.

First, on the client side, the page form data is encapsulated into JSON format through JavaScript scripting. The Getjsondata () function completes this function. Then we send the data to the requestdata.ashx of the server via the $.ajax () method. It uses the Json.stringify () method, which converts the data sent by the client into a JSON object, which can be seen in detail here https://developer.mozilla.org/en-US/docs/Web/ Javascript/reference/global_objects/json/stringify
Copy Code code as follows:

$ ("#btnSend"). Click (function () {
$ ("#request-process-patent"). HTML ("Submitting data, do not close 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 (the request has been submitted!) We will get in touch with you as soon as possible ");
}
},
Error:function (message) {
$ ("#request-process-patent"). HTML ("Submit data Failed!"). ");
}
});
});

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 look at the service-side code, REQUESTDATA.ASHX.
Copy Code code 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;
}
}
}

Defines a class Requestdatajson with the serializable feature attribute to deserialize the client data to obtain the data and store it in the database. EntityFramework is used in the above code to make the database interactive code very concise. There are two types of return results, corresponding to the callback function success () and error () in Ajax. In the success () callback function, if the value of the returned result is greater than 0, the number of records added to the database by EntityFramework; in the error () callback function, the return result shows the specific information of the failure.

The RequestData class inherits the IHttpHandler interface, indicating that it handles client requests in a synchronized manner. Of course, you can also change it to inherit IHttpAsyncHandler interface to handle asynchronous request, the code interface is very 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.