【IT168技术文档】
XMLHttpExecutor
大部分的属性与方法的意义实在不大。我们就来看几个关键方法的实现吧,它们会涉及到WebRequestExecutor的状态,即使我们的实现不同,这些状态一般来说还是保持统一的。
1、构造函数
构造函数的作用其实只是初始化所有的状态,它们分别是:
* responseAvailable属性设为false
* timedOut属性设为false
* aborted属性设为false
* started属性设为false
2、executeRequest方法
调用这个方法就会构造一个XMLHttpRequest对象,并发起一个请求。代码如下:
可以发现,在这个方法被调用之后,started属性被设为了true,以此避免同一个Executor被执行两次。1 function Sys$Net$XMLHttpExecutor$executeRequest() { 2 if (arguments.length !== 0) throw Error.parameterCount(); 3 4 // 通过get_webRequest方法获得当前的WebRequest, 5 // 这个是Sys.Net.WebRequestExecutor的方法。 6 this._webRequest = this.get_webRequest(); 7 8 // 如果已经开始过了,那么抛出异常 9 if (this._started) { 10 throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest')); 11 } 12 13 // 如果没有指定WebRequest,也会抛出异常。 14 if (this._webRequest === null) { 15 throw Error.invalidOperation(Sys.Res.nullWebRequest); 16 } 17 18 // 构造XMLHttpRequest对象并设定各项值 19 var body = this._webRequest.get_body(); 20 var headers = this._webRequest.get_headers(); 21 this._xmlHttpRequest = new XMLHttpRequest(); 22 this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange; 23 var verb = this._webRequest.get_httpVerb(); 24 this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true ); 25 26 // 添加header 27 if (headers) { 28 for (var header in headers) { 29 var val = headers[header]; 30 if (typeof(val) !== "function") 31 this._xmlHttpRequest.setRequestHeader(header, val); 32 } 33 } 34 35 // 如果使用POST方法 36 if (verb.toLowerCase() === "post") { 37 // 则需要设置Content-Type 38 if ((headers === null) || !headers['Content-Type']) { 39 this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 40 } 41 if (!body) { 42 body = ""; 43 } 44 } 45 46 // 如果指定了timeout时间 47 var timeout = this._webRequest.get_timeout(); 48 if (timeout > 0) { 49 // 则取消 50 this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout); 51 } 52 53 this._xmlHttpRequest.send(body); 54 // 表明已经开始了 55 this._started = true; 56 }