Home >Web Front-end >JS Tutorial >JQuery submits data to the server in JSON mode sample code_jquery

JQuery submits data to the server in JSON mode sample code_jquery

WBOY
WBOYOriginal
2016-05-16 16:49:511000browse

JQuery encapsulates Ajax data requests, making this operation 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 following code demonstrates how to encapsulate client form data into JSON format, then send the data to the server through JQuery's Ajax request, and finally store the data in the database. The server is defined as an .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, etc.

First, on the client side, the page form data is encapsulated into JSON format through JavaScript script. The GetJsonData() function completes this function. Then we send the data to RequestData.ashx on the server through the $.ajax() method. The JSON.stringify() method is used, which can convert the data sent by the client into a JSON object. For details, please see here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference /Global_Objects/JSON/stringify

Copy code The code is as follows:

$("#btnSend" ).click(function() {
$("#request-process-patent").html("Submitting data, please 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("The request has been submitted! We will contact you as soon as possible");
}
},
error: function (message) {
$("#request-process-patent").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 code 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 Serializable attribute to return client data Serialize to obtain the data and store it in the database. EntityFramework is used in the above code, which makes the database interaction code very concise. There are two types of return results, corresponding to the callback functions success() and error() in ajax. In the success() callback function, if the value of the return result is greater than 0, it indicates the number of records added to the database through EntityFramework; in the error() callback function, the return result displays the specific information of the failure.

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