js 发送http请求
1、在 JavaScript 中,XMLHttpRequest 是客户端的一个 API,它为浏览器与服务器通信提供了一个便捷通道。
2、发送请求步骤:
// 1、创建 XHR对象(IE6- 为ActiveX对象)
// 2、连接及发送请求
// 3、回调处理
function createXMLHttpRequest() { var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); if (xhr.overrideMimeType) xhr.overrideMimeType('text/xml'); } else if (window.ActiveXObject) { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } return xhr; } var xhr = createXMLHttpRequest(); if (xhr != null) { xhr.open("get", url, true); xhr.send(null); xhr.onreadystatechange = function () { // readyState 五种状态 // 0 - (未初始化)调用了open()方法,未调用send()方法 // 1 - (载入)send()方法,正在发送请求 // 2 - (载入完成)send()方法执行完成,已经接收到全部响应内容 // 3 - (交互)正在解析响应内容 // 4 - (完成)响应内容解析完成 if (xhr.readyState == 4) { // status:http状态码 if (xhr.status >= 200 && xhr.status < 300) { } else { } } } }