首先,在客戶端,通過JavaScript腳本將頁面表單數(shù)據(jù)封裝成JSON格式。GetJsonData()函數(shù)完成了這一功能。然后我們通過$.ajax()方法將數(shù)據(jù)發(fā)送到服務(wù)端的RequestData.ashx。其中用到了JSON.stringify()方法,它可以將客戶端發(fā)送的數(shù)據(jù)轉(zhuǎn)換成JSON對象,詳細(xì)的內(nèi)容可以看這里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
代碼如下:
$("#btnSend").click(function() {
$("#request-process-patent").html("正在提交數(shù)據(jù),請勿關(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("請求已提交!我們會盡快與您取得聯(lián)系");
}
},
error: function (message) {
$("#request-process-patent").html("提交數(shù)據(jù)失敗!");
}
});
});
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;
}
再來看看服務(wù)端的代碼,RequestData.ashx.
代碼如下:
[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; }
}
/// tb_query obj = new tb_query(); try context.Response.ContentType = "text/plain"; public bool IsReusable RequestData類繼承了IHttpHandler接口,表明它是以同步的方式處理客戶端請求。當(dāng)然,你也可以將其改為繼承IHttpAsyncHandler接口來處理異步請求,代碼接口大同小異。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
/// 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
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();
{
using (var ctx = new dbEntities())
{
ctx.tb_query.AddObject(obj);
num = ctx.SaveChanges();
}
}
catch (Exception msg)
{
context.Response.Write(msg.Message);
}
context.Response.Write(num);
}
{
get
{
return false;
}
}
}
定義一個帶有Serializable特征屬性的類RequestDataJSON用來將客戶端數(shù)據(jù)進行反序列化,從而獲取到數(shù)據(jù)并存入數(shù)據(jù)庫。上述代碼中使用了EntityFramework,從而使得數(shù)據(jù)庫的交互代碼變得很簡潔。返回結(jié)果有兩種,對應(yīng)ajax中的回調(diào)函數(shù)success()和error()。在success()回調(diào)函數(shù)中,如果返回結(jié)果的值大于0,則表示通過EntityFramework添加到數(shù)據(jù)庫中的記錄數(shù);在error()回調(diào)函數(shù)中,返回結(jié)果則顯示了失敗的具體信息。