JQuery將Ajax數(shù)據(jù)請(qǐng)求進(jìn)行了封裝,從而使得該操作實(shí)現(xiàn)起來容易許多。以往我們要寫很多的代碼來實(shí)現(xiàn)該功能,現(xiàn)在只需要調(diào)用$.ajax()方法,并指明請(qǐng)求的方式、地址、數(shù)據(jù)類型,以及回調(diào)方法等。下面的代碼演示了如何將客戶端表單數(shù)據(jù)封裝成JSON格式,然后通過JQuery的Ajax請(qǐng)求將數(shù)據(jù)發(fā)送到服務(wù)端,并最終將數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫中。服務(wù)端定義為一個(gè).ashx文件,事實(shí)上你可以將服務(wù)端定義為任何能接收并處理客戶端數(shù)據(jù)的類型,如Web Service,ASP.NET Page,Handler等。
首先,在客戶端,通過JavaScript腳本將頁面表單數(shù)據(jù)封裝成JSON格式。GetJsonData()函數(shù)完成了這一功能。然后我們通過$.ajax()方法將數(shù)據(jù)發(fā)送到服務(wù)端的RequestData.ashx。其中用到了JSON.stringify()方法,它可以將客戶端發(fā)送的數(shù)據(jù)轉(zhuǎn)換成JSON對(duì)象,詳細(xì)的內(nèi)容可以看這里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
復(fù)制代碼 代碼如下:
$("#btnSend").click(function() {
$("#request-process-patent").html("正在提交數(shù)據(jù),請(qǐng)勿關(guān)閉當(dāng)前窗口...");
$.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("請(qǐng)求已提交!我們會(huì)盡快與您取得聯(lián)系");
}
},
error: function (message) {
$("#request-process-patent").html("提交數(shù)據(jù)失敗!");
}
});
});
function GetJsonData() {
var json = {
"classid": 2,
"name": $("#tb_name").val(),
"zlclass": "測(cè)試類型1,測(cè)試類型2,測(cè)試類型3",
"pname": $("#tb_contact_people").val(),
"tel": $("#tb_contact_phone").val()
};
return json;
}
復(fù)制代碼 代碼如下:
[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;
}
}
}
新聞熱點(diǎn)
疑難解答
圖片精選