XMLHttpRequest
1、 XMLHttpRequest
AJAX的核心JavaScript对象XMLHttpRequest对象
a) 创建XMLHttpRequest对象(简单版)
var xmlHttpRequest; function createXMLHttpRequest() { if(window.ActiveXObject) // IE下创建XMLHttpRequest对象 { xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp'); } elseif(window.XMLHttpRequest) // 其他浏览器(如firefox、google) { xmlHttpRequest = new XMLHttpRequest(); } } |
function createXMLHttpRequest(){ // 兼容IE低版本的创建xmlHttpRequest对象的方式 var xmlHttpRequest = null;
try { // 创建IE5或以下的xmlHttpRequest对象 xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) // 创建XMLHttpRequest抛出异常, { try { // 创建IE高版本的XMLHttpRequest对象 xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch(axo) { xmlHttpRequest = null; } }
if ( !xmlHttpRequest && typeof XMLHttpRequest != "undefined" ) { // 非IE下的浏览器创建XMLHttpRequest对象 xmlHttpRequest = new XMLHttpRequest(); } return xmlHttpRequest;
} |
b) XMLHttpRequest对象请求数据
var requestType; function startRequest(httpRequest) { if(xmlHttpRequest) { requestType = httpRequest; createXMLHttpRequest(); xmlHttpRequest.onreadystatechange = handleStateChange; xmlHttpRequest.open("GET","../ajax/paraseXML.xml",true); xmlHttpRequest.send(null); } else { alert('xmlHttpRequest is false'); } } |
c) XMLHttpRequest对象返回数据处理
function handleStateChange() { if (xmlHttpRequest.readyState == 4) { if (xmlHttpRequest.status == 200) { if (requestType == "north") { listNorthStates(); } if (requestType == "all") { listAllStates(); } } } } |