Created
April 7, 2014 04:25
-
-
Save calledt/10014812 to your computer and use it in GitHub Desktop.
javascript XMLHttpRequest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function createXHR() { | |
| if(typeof XMLHttpRequest != undefined) { | |
| return new XMLHttpRequest(); | |
| }else if(typeof ActiveXObject != undefined) { | |
| if(typeof arguments.callee.activeXString != 'string') { | |
| var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp'], | |
| i, len; | |
| for(i = 0, len = versions.length; i < len; i++ ) { | |
| try { | |
| new ActiveXObject(versions[i]); | |
| arguments.callee.activeXString = versions[i]; | |
| break; | |
| }catch(ex) { | |
| } | |
| } | |
| } | |
| }else { | |
| throw new Error("No XHR object available"); | |
| } | |
| } | |
| // 同步请求 | |
| var xhr = createXHR(); | |
| // open不会真正的发送请求,而只是启动一个请求以备发送 | |
| // false表示请求是同步的,代码等待服务器响应之后再继续执行 | |
| xhr.open('GET', URL, false); | |
| // send请求真正被分派到服务器 | |
| xhr.send(null); | |
| if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { | |
| alert(xhr.responseText); | |
| }else { | |
| alert("Request was unsuccessful: " + xhr.status); | |
| } | |
| // 异步请求 | |
| var xhr = createXHR(); | |
| xhr.onreadystatechange = function() { | |
| if (xhr.readyState == 4) { | |
| if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { | |
| alert(xhr.responseText); | |
| }else { | |
| alert("Request was unsuccessful:" + xhr.status); | |
| } | |
| } | |
| }; | |
| xhr.open('GET', URL, true); | |
| xhr.send(null); | |
| // 取消异步请求 | |
| xhr.abort(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment