JQuery将Ajax数据请求进行了封装,从而使得该操作实现起来容易许多。以往我们要写很多的代码来实现该功能,现在只需要调用$.ajax()方法,并指明请求的方式、地址、数据类型,以及回调方法等。下面的代码演示了如何将客户端表单数据封装成JSON格式,然后通过JQuery的Ajax请求将数据发送到服务端,并最终将数据存储到数据库中。
首先,在客户端,通过JavaScript脚本将页面表单数据封装成JSON格式。GetJsonData()函数完成了这一功能。然后我们通过$.ajax()方法将数据发送到服务端的RequestData.ashx。其中用到了JSON.stringify()方法,它可以将客户端发送的JSON数据对象进行序列化操作。
$("#btnSend")。click(function() {
$("#request-process-patent")。html("正在提交数据,请勿关闭当前窗口…");
$.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("请求已提交!我们会尽快与您取得联系");
}
},
error: function (message) {
$("#request-process-patent")。html("提交数据失败!");
}
});
});
function GetJsonData() {
var json = {
"classid": 2,
"name": $("#tb_name")。val(),
"zlclass": "测试类型1,测试类型2,测试类型3",
"pname": $("#tb_contact_people")。val(),
"tel": $("#tb_contact_phone")。val()
};
return json;
}
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64681.shtml