本文實例講述了jQuery使用$.ajax進行異步刷新的方法。分享給大家供大家參考,具體如下:
最近要用到jquery進行異步讀取數據的功能,jquery提供了許多內置的異步讀取函數,給大家演示下最常用的$.ajax用法
在客戶端文本框輸入一個內容,然后在服務器端返回時間
在DEMO中要用到ashx文件,用于獲取服務器的信息
效果圖片
escape() 函數可對字符串進行編碼,這樣就可以在所有的計算機上讀取該字符串。
客戶端代碼
<%@ 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>
服務器端代碼
<%@ 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; } }
完整實例代碼點擊此處本站下載。
希望本文所述對大家jQuery程序設計有所幫助。