The example in this article describes how jQuery uses $.ajax for asynchronous refresh. Share it with everyone for your reference, the details are as follows:
I recently used jquery to read data asynchronously. jquery provides many built-in asynchronous reading functions. I will show you the most commonly used $.ajax usage
Enter a content in the text box on the client side, and then return the time on the server side
The ashx file is used in DEMO to obtain server information
Effect pictures
Theescape() function encodes a string so that it can be read on all computers.
Client code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <mce:script type="text/javascript" src="js/jquery-1.4.2.min.js" mce_src="js/jquery-1.4.2.min.js"></mce:script> <title></title> <mce:script type="text/javascript"><!-- function GetData() { if ($('#Text1').val() == '') { alert('请输入内容!'); return; } $.ajax({ type: "GET", url: "ContentHandler.ashx?name=" + $('#Text1').val(), cache: false, data: { sex: "男" }, success: function(output) { if (output == "" || output == undefined) { alert('返回值为空!'); } else { output = eval("(" + output + ")"); $('#divmsg').html("姓名:" + output.name + "----" + "日期:" + output.dt); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("获取数据异常"); } }); } // --></mce:script> </head> <body> <form id="form1" runat="server"> <div> ajax使用demo </div> <div> <input id="Text1" type="text" /> <input id="Button1" type="button" value="获取数据" onclick="GetData()"/> </div> <div id='divmsg'> </div> </form> </body> </html>
Server side code
<%@ WebHandler Language="C#" Class="ContentHandler" %> using System; using System.Web; public class ContentHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { string output = ""; string name = context.Request.Params["name"]; output = GetJsonData(name); context.Response.ContentType = "text/plain"; context.Response.Write(output); } public bool IsReusable { get { return false; } } public string GetJsonData(string aa) { string result = "{name:/""+aa+"/",dt:/""+DateTime.Now.ToString()+"/"}"; return result; } }
Click here for the complete example codeDownload from this site.
I hope this article will be helpful to everyone in jQuery programming.