底层异步通信机制.docx
- 文档编号:28854929
- 上传时间:2023-07-20
- 格式:DOCX
- 页数:79
- 大小:263.58KB
底层异步通信机制.docx
《底层异步通信机制.docx》由会员分享,可在线阅读,更多相关《底层异步通信机制.docx(79页珍藏版)》请在冰豆网上搜索。
底层异步通信机制
AAjax的使用
1. Aajax底层异步通信机制:
XMLHTTP
对于Aajax是如何实现底层的异步通信呢?
其实关于这一块的技术XMLHttp早就出现了,只不过最近两年才被给予了高度的重视。
在AAjax的客户端框架中,提供了诸如Sys.Net.WebRequest这样的类型,我们可以通过创建一个该类型的对象,并指定其要调用的服务器端的页面地址,以及对应的参数、超时时间等。
但这只不过是对XmlHttp这一技术的包装而已。
1.1.Ajax的技术构成
技术构成如下:
XMLHTTP对象,内置于浏览器中,实现了客户端和服务器端的异步通信。
JSON或者XML,他们定义了客户端和服务器端数据交换的格式。
HTML、CSS,数据表现技术。
JAVASCRIPT,通过JavaScript来操纵浏览器的DOM对象模型,从而实现人机交互。
1.2.定义一个XmlHttp对象
下面的代码就创建了一个跨浏览器的XmlHttp对象的创建方法。
functionCreateXMLHTTP()
{
varxmlhttp;
if(window.XMLHTTPRequest)
{
xmlhttp=newXMLHTTPRequest();
}
elseif(window.ActiveXObject)
{
try
{
xmlhttp=newActiveXObject("Msxml2.XMLHTTP");
}
catch(el)
{
xmlhttp=newActiveXObject("Msxml.XMLHTTP");
}
}
if(xmlhttp==null)
throw"创建xmlHttp对象失败";
else
returnxmlhttp;
}
1.3.XmlHttp对象的Open方法
例如通过上面的方法创建了一个xmlHttp对象,可以按照如下的方式调用它的Open方法。
xmlHttp.Open(http-method,url,async,userID,password)
Open方法中包含了5个参数,前三个是必要的,后两个是可选的(在服务器需要进行身份验证时提供)。
参数的含义如下所示:
http-method:
HTTP的通信方式,比如GET或是POST
url:
接收XML数据的服务器的URL地址。
通常在URL中要指明ASP或CGI程序
async:
一个布尔标识,说明请求是否为异步的。
如果是异步通信方式(true),客户机就不等待服务器的响应;如果是同步方式(false),客户机就要等到服务器返回消息后才去执行其他操作
userID用户ID,用于服务器身份验证
password用户密码,用于服务器身份验证
1.4.XmlHttp异步处理方式
通过设定xmlHttp对象的onreadystatechange属性,我们可以指定当xmlhttp对象的状态发生更改时候的处理函数,如:
xmlhttp.onreadystatechange= HandleStateChange;
1.5.XmlHttp对象的Send方法
用Open方法对xmlHttp对象进行初始化后,调用Send方法发送数据:
xmlhttp.Send(data)
Send方法的参数类型是Variant,可以是字符串、DOM树或任意数据流。
发送数据的方式分为同步和异步两种。
在异步方式下,数据包一旦发送完毕,就结束Send进程,客户机执行其他的操作;而在同步方式下,客户机要等到服务器返回确认消息后才结束Send进程。
1.6.xmlHttp对象的异步处理函数
1.6.1. readyState
XMLHTTP对象中的readyState属性能够反映出服务器在处理请求时的进展状况。
客户机的程序可以根据这个状态信息设置相应的事件处理方法。
属性值及其含义如下表所示:
0(未初始化)
对象已建立,但是尚未初始化(尚未调用open方法)
1(初始化)
对象已建立,尚未调用send方法
2(发送数据)
send方法已调用,但是当前的状态及http头未知
3(数据传送中)
已接收部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误,
4(完成)
数据接收完毕,此时可以通过通过responseBody和responseText获取完整的回应数据
1.6.2. 客户机处理响应信息
客户机接收到返回消息后,进行简单的处理,基本上就完成了C/S之间的一个交互周期。
客户机接收响应是通过XMLHTTP对象的属性实现的:
responseTxt:
将返回消息作为文本字符串;
responseXML:
将返回消息视为XML文档,在服务器响应消息中含有XML数据时使用;
responseStream:
将返回消息视为Stream对象
1.6.3. status
通过判断XMLHTTP对象的status,我们可以具体的判断本次请求的实际情况,成功,失败,根据这些状态码我们就可以调用执行成功或者失败的回调函数。
长整形标准xmlhttp状态码,定义如下:
Number
Description
100
Continue
101
Switchingprotocols
200
OK
201
Created
202
Accepted
203
Non-AuthoritativeInformation
204
NoContent
205
ResetContent
206
PartialContent
300
MultipleChoices
301
MovedPermanently
302
Found
303
SeeOther
304
NotModified
305
UseProxy
307
TemporaryRedirect
400
BadRequest
401
Unauthorized
402
PaymentRequired
403
Forbidden
404
NotFound
405
MethodNotAllowed
406
NotAcceptable
407
ProxyAuthenticationRequired
408
RequestTimeout
409
Conflict
410
Gone
411
LengthRequired
412
PreconditionFailed
413
RequestEntityTooLarge
414
Request-URITooLong
415
UnsupportedMediaType
416
RequestedRangeNotSuitable
417
ExpectationFailed
500
InternalServerError
501
NotImplemented
502
BadGateway
503
ServiceUnavailable
504
GatewayTimeout
505
HTTPVersionNotSupported
如:
functionHandleStateChange()
{
if(xmlhttp.readyState==4) //客户端已经完全加载完毕
{
if(xmlhttp.status==200)
{
alert("Result="+xmlhttp.responseXML.xml);
//成功执行,调用成功执行的回调函数
}
else
{
}
//…
}
else
….
}
2. AAjax系统框架
AAjax提供了完整的客户端和服务器端的模型框架。
客户端与服务器端的通信模型。
2.1.客户端框架
只要当前的页面中,包含引用ScriptManager控件,系统就会将“MicrosoftAjax.js”加载到客户端,完成整个客户端架构的构建。
关于客户端的架构结构请参考下图:
具体的类库截图如下:
2.2.服务器端框架
服务器端的模型分层如下:
AAjax框架提供的服务器端的类库如下:
3. 针对JavaScript基本类型的扩展
JavaScript是一门非常强大的基于对象(ObjectBased)的语言,但是对面向对象(ObjectOriented)的支持还存在一些不足,同时JavaScript内建的类库也比较简单,甚至缺乏一些很常用的功能。
ASP.NETajax在运行时扩展了JavaScript,大大增强了它的面向对象支持能力,并扩展了一些开发时常用的操作。
3.1.String对象的扩展
Name
Description
endsWithFunction
DetermineswhethertheendoftheStringobjectmatchesthespecifiedstring.
formatFunction
ReplaceseachformatiteminaStringobjectwiththetextequivalentofacorrespondingobject'svalue.
localeFormatFunction
ReplacestheformatitemsinaStringobjectwiththetextequivalentofacorrespondingobject'svalue.Thecurrentcultureisusedtoformatdatesandnumbers.
startsWithFunction
DetermineswhetherthestartoftheStringobjectmatchesthespecifiedstring.
trimFunction
RemovesleadingandtrailingwhitespacefromaStringobjectinstance.
trimEndFunction
RemovestrailingwhitespacefromaStringobjectinstance.
trimStartFunction
RemovesleadingwhitespacefromaStringobjectinstance.
3.2.Array对象的扩展
Name
Description
addFunction
AddsanelementtotheendofanArrayobject.
addRangeFunction
CopiesalltheelementsofthespecifiedarraytotheendofanArrayobject.
clearFunction
RemovesallelementsfromanArrayobject.
cloneFunction
CreatesashallowcopyofanArrayobject.
containsFunction
DetermineswhetheranelementisinanArrayobject.
dequeueFunction
RemovesthefirstelementfromanArrayobject.
enqueueFunction
AddsanelementtotheendofanArrayobject.
note
UsetheaddfunctioninsteadoftheArray.enqueuefunction.
forEachFunction
PerformsaspecifiedactiononeachelementofanArrayobject.
indexOfFunction
SearchesforthespecifiedelementofanArrayobjectandreturnsitsindex.
insertFunction
InsertsavalueatthespecifiedlocationinanArrayobject.
parseFunction
CreatesanArrayobjectfromastringrepresentation.
removeFunction
RemovesthefirstoccurrenceofanelementinanArrayobject.
removeAtFunction
RemovesanelementatthespecifiedlocationinanArrayobject.
3.3.Date对象的扩展
Name
Description
formatFunction
Formatsadatebyusingtheinvariant(culture-independent)culture.
localeFormatFunction
Createsadatefromalocale-specificstringusingthecurrentculture.
parseLocaleFunction
Createsadatefromalocale-specificstringusingthecurrentculture.
parseInvariantFunction
Createsadatefromastringusingtheinvariantculture.
3.4.Number对象的扩展
Name
Description
formatFunction
Formatsanumberbyusingtheinvariantculture.
localeFormatFunction
Formatsanumberbyusingthecurrentculture.
parseInvariantFunction
Returnsanumericvaluefromastringrepresentationofanumber.
parseLocaleFunction
Createsanumberfromalocale-specificstring.
3.5.Error
Name
Description
argumentFunction
CreatesanErrorobjectthatrepresentstheSys.ArgumentExceptionexception.
argumentNullFunction
CreatesanErrorobjectthatrepresentstheSys.ArgumentNullExceptionexception.
argumentOutOfRangeFunction
CreatesanErrorobjectthatrepresentstheSys.ArgumentOutOfRangeExceptionexception.
argumentTypeFunction
CreatesanErrorobjectthatrepresentstheSys.ArgumentTypeExceptionexception.
argumentUndefinedFunction
CreatesanErrorobjectthatrepresentstheSys.ArgumentUndefinedExceptionexception.
createFunction
CreatesanErrorobjectthathasoptionaladditionalerrorinformation.
invalidOperationFunction
CreatesanErrorobjectthatrepresentstheSys.InvalidOperationExceptionexception.
notImplementedFunction
CreatesanErrorobjectthatrepresentstheSys.NotImplementedExceptionexception.
parameterCountFunction
CreatesanErrorobjectthatrepresentstheSys.ParameterCountExceptionexception.
popStackFrameFunction
UpdatesthefileNameandlineNumberpropertiesofanErrorinstancetoindicatewheretheerrorwasthrowninsteadofwheretheerrorwascreated.Usethisfunctionifyouarecreatingcustomerrortypes.
3.6.Sys.StringBuilder类
3.6.1. Constructors
StringBuilderConstructor
CreatesanewinstanceofStringBuilderandoptionallyacceptsinitialtexttoconcatenate.
3.6.2. Members
appendMethod
AppendsastringtotheendoftheStringBuilderinstance.
appendLineMethod
AppendsanewstringwithalineterminatortotheendoftheStringBuilderinstance.
clearMethod
ClearsthecontentsoftheStringBuilderinstance.
isEmptyMethod
DetermineswhethertheStringBuilderinstancehasanycontent.
toStringMethod
CreatesastringfromthecontentsofaStringBuilderinstance.
3.7.Object
新增的如下两个方法:
Name
Description
getTypeFunction
Returnsthetypeofaspecifiedobjectinstance.
getTypeNameFunction
Returnsastringthatidentifiestherun-timetypenameofanobject.
3.8.使用举例
3.8.1. String
vara="abc";
//同C#
document.write(a.startsWith("a"));
document.write("");
document.write(a.endsWith("c"));
document.write("
");
a=a.trimStart();
document.write(a.startsWith("a"));
document.write("
");
a=a.trimEnd();
document.write(a.endsWith("c"));
document.write("
");
a=""+a+"";
a=a.trim();
document.write(a.startsWith("a"));
document.write("");
document.write(a.endsWith("c"));
document.write("
");
varuser=
{
Name:
"webabcd",
Birthday:
newDate(1980,2,14)
};
//String.localeFormat();
document.write(String.format("Name:
{0},Birthday:
{1:
yyyy-MM-dd}",user.Name,user.Birthday));
document.write("
");
//自定义格式化的实现
Type.registerNamespace('Dem
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 底层 异步 通信 机制