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