function showList(data) {
console.log(data)
}
var xhr = null;
ajaxFunc('post', './data.php', 'username=liao', true, showList)
function ajaxFunc(method, url, data, flag, callback) {
// 兼容处理
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
method = method.toUpperCase();
xhr.open(method, url, flag); // method url 同步异步
if (method == 'POST') {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // post请求必须设置头部
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(xhr.responseText)
}
}
}
xhr.send(data);
}
详细描述
属性 | 描述 |
---|---|
XMLHttpRequest | 所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject) |
open(method,url,async) | 规定请求类型,url,是否同步异步 1.method:请求的类型,GET 或 POST 2.url:文件在服务器上的位置 3.async:true(异步)或 false(同步) |
send(string) | 将请求发送到服务器,string仅用于post请求 |
setRequestHeader(header,value) | 向请求添加 HTTP 头。header: 规定头的名称。value: 规定头的值 |
onreadystatechange | 状态改变的时间触发器 |
readyState | 对象状态(integer),状态值 0 = 未初始化,未调用send()方法 1 = 读取中,已调用send()方法,正在发送请求 2 = 已读取,send()方法已完成,接受到全部响应内容 3 = 交互中,正在解析响应内容 4 = 完成,响应内容全部完成 |
responseText | 获得字符串形式的响应数据 |
responseXMl | 获得XML形式的相应数据 |
status | 服务器返回的状态码,如:404 = 文件没找到,200 = 成功,500 = 服务器内部错误,304 = 资源被修改 |
statusText | 服务器返回的状态文本信息 |