Json實現非同步請求(提交評論)
主要將代碼粘貼,通過閱讀代碼理解其中的相關邏輯。
html代碼:
已有評論:
js代碼:
$("#send").click(function () { $.get("doSave.ashx", { //調用json外掛程式 u_name: $("#username1").val(), //json資料/值對化 u_cont: $("#content").val() }, function (data) var uName = data.username; //註:此處的username與doSave.ashx中的dic.add("username",uname)中的username相對應的 var uCont = data.content; var txtHtml = "" + uName + ":" + uCont + "
" $("#resText").html(txtHtml); //將返回的資料添加到頁面上 }, "json"); })
外掛程式代碼:
<%@ WebHandler Language="C#" Class="doSave" %>using System;using System.Web;public class doSave : IHttpHandler{ public void ProcessRequest(HttpContext context) { var dic = new System.Collections.Generic.Dictionary(); //儲存的集合 string jsonStr = "{}"; //建立字串jsonStr context.Response.ContentType = "text/json"; //定義返回的內容類型為json string uname = context.Request.QueryString[0]; //擷取請求參數中第一個參數,也可以直接使用uname string commet = context.Request.QueryString[1]; //定義字串uname、commet為context請求查詢的字串context.Request.Params["username"];QyertStrubg:查詢字串 dic.Add("username", uname); //將字串添加到對象中 dic.Add("content", commet); jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dic); //序列化集合為json字串 context.Response.Write(jsonStr); } public bool IsReusable { get { return false; } }}
此處效果即為,在輸入框中輸入相關文字,點擊提交,下方會自動將書寫的文字進行展示,無需跳轉其他頁面。