第六篇 ajax
加载异步数据
6-1 加载异步数据
XMLHttpRequest--传统的JavaScript方法实现Ajax功能
6-1-a
<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>XMLHttpRequest--传统的JavaScript方法实现Ajax功能</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script> var objXmlHttp = null //声明一个空的XMLHTTP变量 function CreateXMLHttp() { //根据浏览器的不同,返回该变量的实体对象 if(window.ActiveXObject) { objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else { if(window.XMLHttpRequest) { objXmlHttp = new XMLHttpRequest(); } else { alert("初始化XMLHTTP错误!"); } } } function GetSendData() { // document.getElementById("divTip").innerHTML = "<img alt='' title='' src='' />"; // var strSendUrl = "6-1-b.html?date=" + Date(); // CreateXMLHttp(); // objXmlHttp.open("GET",strSendUrl,true); objXmlHttp.onreadystatechange = function() { if(objXmlHttp.readyState == 4) { if(objXmlHttp.statue == 200) { // document.getElementById("divTip").innerHTML = objXmlHttp.responseText; } } } // objXmlHttp.send(null); } </script> </head> <body> <div class="divFrame"> <div class="divTitle"> <input id="Button1" type="button" onclick="GetSendData()" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> </div> </div> </body> </html>
6-1-b
<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> </style> <script type="text/javascript" src="js/jquery-1.12.3.min.js"></script> <script> </script> </head> <body> <div class="clsShow"> 姓名:陶国荣<br /> 性别:男<br /> 邮箱:tao_guo_rong@163.com </div> </body> </html>
6-2 jQuery:load()方法
load(url,[data],[callback]) --获取异步数据
--url:被加载的页面技术
--[data]:表示发送到服务器的数据,格式为:key/value
--[callback]:回调函数
<!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> <title></title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //load(url,[data],[callback]) --获取异步数据 //url--被加载的页面技术 //[data]--表示发送到服务器的数据,格式为:key/value //[callback]--回调函数 $("#Button1").click(function () { $("#divTip").load("a.htm .clsShow", function (data) { $("#divTip").html(data) }); //a.htm .clsShow a.htm页面中类别名为.clsShow的全部元素 //$("#divTip").load("a.htm"); }); }) </script> </head> <body> <h2>6-2-a</h2> <div class="divFrame"> <div class="divTitle"> <input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> </div> </div> </body> </html>
6-3 getJSON()
<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>getJSON</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script type="text/javascript" src="js/jquery-1.12.3.min.js"></script> <script> $(function(){ //******* //JSON文件格式--一种轻量级的数据交互格式 //$.getJSON(url,[data],[callback]) //--url:被加载的页面技术 //--[data]:表示发送到服务器的数据,格式为:key/value //--[callback]:回调函数 $("#Button1").click(function(){ // $.getJSON('demo.js',function(date){ $("#divTip").empty(); var strHTML=""; $.each(date,function(InfoIndex,Info){ strHTML += "姓名:" + Info["name"] + "<br>"; strHTML += "性别:" + Info["sex"] + "<br>"; strHTML += "邮箱:" + Info["email"] + "<hr>"; }) $("#divTip").html(strHTML); }) }) }) </script> </head> <body> <h2>6-3:getJSON</h2> <div class="divFrame"> <div class="divTitle"> <input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> </div> </div> </body> </html>
6-4 getScript()
全局函数getScript()获取.js文件的内容.
<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>getScript</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script type="text/javascript" src="js/jquery-1.12.3.min.js"></script> <script> //****** //$.getScript(url,[callback]) $(function(){ // $("#Button1").click(function(){ // $.getScript("UserInfo.js",function(){ $("#test").html("ok!"); }); }) }) </script> </head> <body> <h2>6-4:getScript</h2> <div class="divFrame"> <div class="divTitle"> <input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> <div id="test"></div> </div> </div> </body> </html>
js文件
// JavaScript Document var data =[ { "name":"吴者然", "sex":"男", "email":"demo1@123.com" }, { "name":"吴中者", "sex":"男", "email":"demo2@123.com" }, { "name":"何开", "sex":"女", "email":"demo3@123.com" }, { "name":"zq", "sex":"man", "email":"zq@zq.com" } ] var strHTML=""; $.each(data,function(){ strHTML += "姓名:" + this["name"] + "<br>"; strHTML += "性别:" + this["sex"] + "<br>"; strHTML += "邮箱:" + this["email"] + "<hr>"; }); $("#divTip").html(strHTML);
6-5 异步加载XML文档
$.get(url,[data],[callback],[type])
--url:加载的数据地址
--[data]:发送到服务器的数据,key/value
--[callback]:加载成功时执行的回调函数
--[type]:返回数据的格式--html,xml,js,json,text
<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>get()--XML</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script type="text/javascript" src="js/jquery-1.12.3.min.js"></script> <script> $(function(){ $("#Button1").click(function(){ //打开文件,并通过回调函数处理获取的数据 $.get("UserInfo.xml",function(data){ var strHTML=""; $(data).find("User").each(function() { var $strUser = $(this); strHTML += "姓名:" + $strUser.find("name").text()+"<br>"; strHTML += "性别:" + $strUser.find("sex").text()+"<br>"; strHTML += "邮箱:" + $strUser.find("email").text()+"<hr>"; }); $("#divTip").html(strHTML); }); }) }) </script> </head> <body> <h2>6-5:XML</h2> <div class="divFrame"> <div class="divTitle"> <input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> <div id="test"></div> </div> </div> </body> </html>
xml:
<?xml version="1.0" encoding="utf-8"?> <Info> <User id ="1"> <name>qq</name> <sex>male</sex> <email>qq@qq.com</email> </User> <User id ="2"> <name>ww</name> <sex>female</sex> <email>ww@ww.com</email> </User> </Info>
请求服务器数据
6-6 $.get()向服务器请求数据
***客户端向服务器传递参数时,使用的格式是{key0:value0,key1:value1,.......},"key0"为参数名称,"value0"为参数的值。
***如果参数的值是中文格式,必须通过使用encodeURI()进行转码,当然,在客户端接受时,使用decodeURL()进行解码。
<!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> <title>get</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} #txtName { width: 122px; } </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#Button1").click(function () { //打开文件,并通过回调函数返回服务器响应后的数据 $.get("UserInfo.aspx", { name: encodeURI($("#txtName").val()) }, function (data) { $("#divTip").empty().html(data); }); }); }) </script> </head> <body> <h2>6-6:get()</h2> <div class="divFrame"> <div class="divTitle"> 姓名:<input id="txtName" type="text" /><input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> <div id="test"></div> </div> </div> </body> </html>
服务器端文件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserInfo.aspx.cs" Inherits="WebApplication1.UserInfo" %> <% string strName = System.Web.HttpUtility.UrlDecode(Request["name"]); string strHTML = "<div class='clsShow'>"; if (strName == "qq") { strHTML += "name:qq<br>"; strHTML += "sex:qq<br>"; strHTML += "mail:qq@qq.com<hr>"; } else if (strName == "ww") { strHTML += "name:ww<br>"; strHTML += "sex:ww<br>"; strHTML += "mail:ww@ww.com<hr>"; } else { strHTML += "没有找到!<hr>"; } strHTML += "</div>"; Response.Write(strHTML); %>
6-7 $.post()
**$.get()与$.post()区别:
**GET方式不适合传递数据量较大的数据,其请求的历史信息会保存在浏览器的缓存中;POST则不存在
--$.post(url,[data],[callback],[type])
<!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> <title>post</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} #txtName { width: 122px; } </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#Button1").click(function () { // $.post("UserInfo.aspx", { name: encodeURI($("#txtName").val()) }, function (data) { $("#divTip").empty().html(data); }); }); }) </script> </head> <body> <h2>6-7:post()</h2> <div class="divFrame"> <div class="divTitle"> 姓名:<input id="txtName" type="text" /><input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> <div id="test"></div> </div> </div> </body> </html>
6-8 serialize()序列化表单
**serialize()方法可以很完美地模拟浏览器提交表单的操作,同时自动解决了中文编码的问题,但它自身有很多不足,如表单中有多项被选中时,该方法只能传递一项的值。因此,在选择传递参数时,须慎重考虑。
<!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> <title>serialize()序列化表单</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#Button1").click(function () { // //serialize()序列化表单 $.post("UserInfo2.aspx", $("#frmUserInfo").serialize(), function (data) { $("#divTip").empty().html(data); }); /* $.post("UserInfo2.aspx", { name: encodeURI($("#txtName").val()), sex:encodeURI($("#txtSex").val()) }, function (data) { $("#divTip").empty().html(data); }); */ }); }) </script> </head> <body> <h2>6-8:serialize()</h2> <form id="frmUserInfo"> <div class="divFrame"> <div class="divTitle"> 姓名:<input id="txtName" type="text" /><br /> 邮箱:<input id="txtSex" type="text" /><br /> <input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="divContent"> <div id="divTip"></div> <div id="test"></div> </div> </div> </form> </body> </html>
$.ajax()方法
6-9 $.ajax([options])
**参数
--url:string 发送请求的地址
--type:string 数据请求方式(post/get),默认是get
--data:string/object 发送到服务器的数据,字符串格式(get:字符串在URL后面)
--dataType:string 服务器返回的数据类型。html,script,text,xml,json
--beforeSend:function
--complete:function 请求完成后调用的回调函数
--success:function 请求成功后调用的回调函数,有两个参数,一个是根据参数dataType处理后服务器返回的数据,另一个是strStatus,用于描述成功请求类型的字符串
--error:function 请求失败后调用的回调函数
--timeout:Number 请求超时的时间(毫秒)
--global:boolean 是否响应全局事件
--async:boolean 是否为异步请求,true,false
--cache:boolean 是否进行页面缓存,true,false
Login.htm
<!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> <title></title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#btnLogin").click(function () { var userName = encodeURI($("#txtName").val()); var userPass = encodeURI($("#txtPass").val()); $.ajax({ url: "Login.aspx", typr:"post", dataType: "text", data: { txtName: encodeURI($("#txtName").val()), txtPass: encodeURI($("#txtPass").val()) }, success: function (data) { if (data == "1") { $("#divError").show().html("ok!"); //alert(data); } else { //alert(data); $("#divError").show().html("error!"); } } }) }); }) </script> </head> <body> <div class="divFrame"> <div class="divTitle"> <span>用户登录</span> </div> <div class="divContent"> <div class="clsShow"> <div id="divError" class="clsError"></div> <div>名称:<input id="txtName" type="text" class="txt" /></div> <div>密码:<input id="txtPass" type="text" class="txt" /></div> <div> <input id="btnLogin" type="button" value="登录" class="btn" /> <input id="btnReset" type="button" value="取消" class="btn" /> </div> </div> </div> </div> </body> </html>
Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebApplication1.Login" %> <% string strName = System.Web.HttpUtility.UrlDecode(Request["txtName"]); string strPass = System.Web.HttpUtility.UrlDecode(Request["txtPass"]); var blnLogin = 0; if (strName == "admin" && strPass == "admin") { blnLogin = 1; } Response.Write(blnLogin); %>
**$.ajax()方法时jQuery中最底层的方法,全局函数$.getScript(),$.get(),$.post(),$.getJSON()都可以用$.ajax()方法进行代替。
6-10 $.ajaxSetup()设置全局Ajax
**$.ajaxSetup([options]) , [options]是一个对象,通过该对象可以设置$.ajax()方法中的参数。
<!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> <title>$.ajaxSetup()方法全局设置ajax</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .btn{ border:#666 1px solid; padding:2px; width:80px;} </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //全局设置 $.ajaxSetup({ type: "GET", url: "UserInfo.xml", dataType: "xml" }); $("#Button1").click(function () { success: function (data) { //ShowData(data, "姓名", "name"); $("#divTip").html("姓名"); } }); $("#Button2").click(function () { success: function (data) { //ShowData(data, "性别", "sex"); $("#divTip").html("性别"); } }); $("#Button3").click(function () { success: function (data) { //ShowData(data, "邮箱", "email"); $("#divTip").html("邮箱"); } }); /* *showData *d为请求响应后的数据 *n为数据中文说明字符 *v为数据在响应数据中的元素名称 */ function ShowData(d, n, v) { $("#divTip").empty(); var strHTML = ""; $(d).find("User").each(function () { var $strUser = $(this); strHTML += n + ":" + $strUser.find(v).text() + "<hr>"; }); $("#divTip").html(strHTML); } }) </script> </head> <body> <div class="divFrame"> <div class="divTitle"> <span><input id="Button1" value="姓名" type="button" class="btn" /></span> <span><input id="Button2" value="性别" type="button" class="btn" /></span> <span><input id="Button3" value="邮箱" type="button" class="btn" /></span> </div> <div class="divContent"> <div id="divTip" class="clsShow"></div> </div> </div> </body> </html>
UserInfo.xml
<?xml version="1.0" encoding="utf-8" ?> <Info> <User id ="1"> <name>qq</name> <sex>male</sex> <email>qq@qq.com</email> </User> <User id ="2"> <name>ww</name> <sex>female</sex> <email>ww@ww.com</email> </User> </Info>
Ajax中的全局事件
--ajaxComplete(callback)
--ajaxError(callback)
--ajaxSend(callback)
--ajaxStart(callback)
--ajaxStop(callback)
--ajaxSuccess(callback)
<!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> <title>Ajax中的全局事件</title> <style type="text/css"> body{ font-size:13px;} .divFrame{ width:260px; border:solid 1px #666;} .divFrame .divTitle{ padding:5px; background-color:#eee;} .divFrame .divContent{ padding:8px;} .divFrame .divContent .clsShow{ font-size:14px;} .clsTip{ display:none;} .btn{ border:#666 1px solid; padding:2px; width:80px;} #txtData { width: 115px; } </style> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { // $("#divMsg").ajaxStart(function () { $(this).show(); }); $("#divMsg").ajaxStop(function () { $(this).html("已成功获取数据").hide(2000); }); $("#Button1").click(function () { $.ajax({ type: "GET", url: "GetData.aspx", data: { txtData: encodeURI($("#txtData").val()) }, dataType: "html", success: function (data) { var str = decodeURI(data).substr(0, 2); $("#divTip").html(str); } }); }); }) </script> </head> <body> <div class="divFrame"> <div class="divTitle"> <span>数据:<input id="txtData" type="text" /></span> <span><input id="Button1" type="button" value="发送" class="btn" /></span> </div> <div class="divContent"> <div id="divMsg" class="clsTip"></div> <div id="divTip" class="clsShow"></div> </div> </div> </body> </html>
GetData.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetData.aspx.cs" Inherits="WebApplication1.GetData" %> <% string strName = Request["txtData"]; Response.Write(strName); %>