JavaScript中利用Ajax 实现客户端与服务器端通信(九)
一:Ajax (Asynchronous JavaScript and XML)不是一个新的技术,事实上,它是一些旧有的成熟的技术以一种全新的更加强大的方式整合在一起
第二的请求步:创建好XML HTTP请求对象后,可用Open()方法来指定要发送
oRequest.open(“get”,”example.txt”,false);
该方法有三个参数:
1、要发送的请求的类型:GET、POST、Header等
2、请求的URL
3、异步(true)或同步(false)
oRequest.open(“get”,”example.txt”,false);
该方法有三个参数:
1、要发送的请求的类型:GET、POST、Header等
2、请求的URL
3、异步(true)或同步(false)
// JScript 文件 function CreateHttpRequest() { var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i=0; i < arrSignatures.length; i++) { try { var oRequest = new ActiveXObject(arrSignatures[i]); return oRequest; } catch (oError) { //ignore } } throw new Error("MSXML is not installed on your system."); } var Http = new Object(); Http.Get=function(url,fnLoading,fnCallBack) { var oRequest = CreateHttpRequest(); if (oRequest){ oRequest.open("get",url,true);
//设置回调函数 oRequest.onreadystatechange = function() { if (oRequest.readyState == 4) {
//成功进行回调 把数据返回 if (fnCallBack) fnCallBack(oRequest.responseText); }else { if (fnLoading) fnLoading(); } } oRequest.send(null); } }
HTML页面:
<!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> <script type="text/javascript" src="js/Http.js"></script> <script type="text/javascript"> function send() { var fnLoading =function() { var oDiv = document.getElementById("divLoading"); if (oDiv) { oDiv.innerHTML="<font color='red'>Loading...</font>"; } } var fnCallBack = function(result) { var oDiv = document.getElementById("divLoading"); oDiv.innerHTML = result; } Http.Get("Default.aspx",fnLoading,fnCallBack); } </script> </head> <body> <div id="divLoading"></div> <input type="button" id="btnSend" value="Send" onclick="send()"/> </body> </html>
后台请求的页面的C#代码:
System.Threading.Thread.Sleep(2000);
Response.Write("ok");
每个HTTP请求发送时都包含一组带有额外信息的首部.在我们使用浏览器时,这些首部被隐藏了,因为对于终端用户来讲,这些信息是没用的.然而,这些首部信息对开发人员来说可能是很重要的
1、getAllResponseHeaders()方法
用于返回所有响应的HTTP首部信息
2、getResponseHeader(“参数“)
用于获取指定的某个首部
3、setRequestHeader(“myheader”,”value”);
用于设置XML HTTP请求的首部信息
Content-Type: text/xml; charset=utf-8
oRequest.getAllResponseHeaders() //得到上述信息
oRequest.getResponseHeader(“Content-Type”)
//text/xml; charset=utf-8
oRequest.setRequestHeader(“myHeader”,”myvalue”);
这里可以假设你设计了一些服务器逻辑来根据这些首部信息提供额外的功能或者对请求的计算
与Get请求一样,POST请求的参数也必须进行编码,并用&进行分割,尽管这此参数不会被附加到URL上,发送POST请求时,要将参数传入send()方法:
oRequst.open(“post”,”http://www.myweb.com/login.aspx”,false);
oRequest.send(“username=admin&password=123”);
注意:利用post方法进和ajax请求时:必须将请求“Content-Type”首部设置为”application/x-www-form-urlencoded”,故:
oRequst.open(“post”,”http://www.myweb.com/login.aspx”,false);
oRequst.setRequestHeader(“Content-Type”,” application/x-www-form-urlencoded”);
oRequest.send (“username=admin&password=123”);
一个小实例登录:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %> <!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"> <title>无标题页</title> <script type="text/javascript" src="js/Http.js"></script> <script type="text/javascript"> function send() { var fnLoading =function() { var oDiv = document.getElementById("divLoading"); if (oDiv) { oDiv.style.display="block"; // oDiv.innerHTML="<font color='red'>Loading...</font>"; } } var fnCallBack = function(result) { var oDiv = document.getElementById("divLoading"); oDiv.style.display="none"; if (result=="success") { location.href="Main.aspx"; }else { alert("帐号或密码有误,请重试!"); } } var user = document.getElementById("txtUser").value; var password = document.getElementById("txtPass").value; var url = "LoginHandler.aspx?user="+user+"&password="+password+"&catch="+(new Date()).getTime() alert(url); Http.Get(url,fnLoading,fnCallBack); } </script> </head> <body> <form id="form1" runat="server"> <div> <div id="divLoading" style="width:100px;height:20px;background-color:Green;color:White;text-align:center;position:absolute;left:0px;top:0px;padding-top:3px;display:none">Loading....</div> <br /> <br /> <asp:Label ID="Label1" runat="server" Text="用户名"></asp:Label> <asp:TextBox ID="txtUser" runat="server"></asp:TextBox> <br /> <asp:Label ID="Label2" runat="server" Text="密码"></asp:Label> <asp:TextBox ID="txtPass" runat="server" TextMode="Password"></asp:TextBox> <br /> <asp:Button ID="btnLogin" runat="server" Text="登陆" OnClientClick="send()" /> <input id="Reset1" type="reset" value="重置" /></div> </form> </body> </html>
后台代码:
public partial class LoginHandler : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request["user"] != null && Request["password"] != null) { string user = Request.QueryString["user"]; string password = Request.QueryString["password"]; if (user == "admin" && password == "123") Response.Write("success"); else Response.Write("error"); } } }
四:Json
JSON示例
从语法方面来看,这与名称/值对相比并没有很大的优势,但是在这种情况下 JSON
更容易使用,而且可读性更好
{ “employees": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
] }
这比相应的XML格式表示的数据更加简洁:
var company =
{ “employees": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
]
};这样将创建一个JavaScript对象
var Http= { XMLHttpRequest:function() { try { var oRequest = new XMLHttpRequest(); return oRequest; }catch(ex) { var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i=0; i < arrSignatures.length; i++) { try { var oRequest = new ActiveXObject(arrSignatures[i]); return oRequest; } catch (oError) { //ignore } } } throw new Error("MSXML is not installed on your system."); }, Get: function (sURL, fnCallback,fnLoading) { var oRequest = new Http.XMLHttpRequest(); oRequest.open("get", sURL, true); oRequest.onreadystatechange = function () { if (oRequest.readyState == 4) { if (fnCallback) fnCallback(oRequest.responseText); }else if (fnLoading) //call loading function... { if (fnLoading) fnLoading(); } } oRequest.send(null); } }
类似于java的错误基类Exception,javascript有个基类Error,Error对象有以下特征:
Error对象的名称对应于它的类,可以是以下值之一
1、EvalError: 错误发生在eval()函数中
2、RangeError:数字的值超过javascript可表示的范围
3、ReferenceError: 使用了非法的引用
4、SyntaxError: 在eval()函数调用中发生了语法错误。
5、TypeError:变量的类型不是预期所需的
6、URIError: 在encodeURI()或者decodeURI()函数中发生的错误
说明:Mozzilla和IE均扩展了Error对象,如IE中提供了一个number特性来表示错误代号,也可用description代替message
引入throw语句,用于有目的的抛出异常
语法如下:throw error_object
error_object可以是字符串、数字、布尔值或是实际的对象。如:
throw “an error occurred”;
throw 5007;
throw true;
throw new Object();
throw new Error();
throw new Error(“error”);
throw new Error(10001,”error”);
其他Error子类也可以使用
如:
throw new SytaxError(“语法错误”);
throw new TypeError(“数据类型有误”);
throw new EvalError(“Eval类型错误”);