Json implements asynchronous requests to submit comments without jumping to another page
- 2020-03-30 04:04:58
- OfStack
Paste the code and read the code to understand the logic.
HTML code:
<form id="form1" runat="server">
<p>
Comment on: </p>
<p>
Name: <input type="text" name="username" id="username1" /></p>
<p>
Content: <textarea name="content" id="content" rows="2" cols="20"></textarea></p>
<p>
<input type="button" id="send" value=" submit " /></p>
</form>
<div class="comment">
Already reviewed: </div>
<div id="resText">
</div>
Js code:
$("#send").click(function () {
$.get("doSave.ashx", {<span style="white-space:pre"> </span> <span style="font-family: Arial, Helvetica, sans-serif;"> </span>//Calling the json plug-in
u_name: $("#username1").val(), //Json data/value pairing
u_cont: $("#content").val()
}, function (data)
var uName = data.username; //Note: the username here corresponds to the username in dic.add("username",uname) in dosave.ashx
var uCont = data.content;
var txtHtml = "<div class='comment'><h6>"
+ uName + ":</h6><p class='para'>"
+ uCont + "</p></div>"
$("#resText").html(txtHtml); //Adds the returned data to the page
}, "json");
})
Plug-in code:
<%@ 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, object>(); //Stored collection
string jsonStr = "{}"; //New string jsonStr
context.Response.ContentType = "text/json"; //Define the returned content type to be json
string uname = context.Request.QueryString[0]; //Gets the first parameter in the request parameter, or you can use uname directly
string commet = context.Request.QueryString[1]; //Define the string uname, the string context.request-params ["username"] that commet queries for the context Request; QyertStrubg: query string
dic.Add("username", uname); //Adds a string to an object
dic.Add("content", commet);
jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dic); //Serialize the collection as a json string
context.Response.Write(jsonStr);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Here the effect is, in the input box to enter the relevant text, click submit, below will automatically write the text for display, without jumping to other pages.