Ajax 函数, 用来与后端的交互 (请求类型有 POST GET DELETE PUT HEAD, 请求地址, callback 请求的回调函数, 参数, 是否异步)
- function Ajax(method, url, callback, data, flag) {
- // xhr 用来存储请求与响应的信息
- var xhr = null;
- if(Windows.XMLHttpRequest) {
- xhr = new XMLHttpRequest();
- }else {
- xhr = new ActiveXObject('Microsoft.XMLHttp');
- }
- // // 监听数据请求状态 监听状态 readyState 的变化
- xhr.onreadystatechange = function() {
- // // 1 2 3
- if(xhr.readyState == 4) {
- // // 4xx url data
- if(xhr.status == 200) {
- callback(xhr.responseText);
- }else {
- console.log('error');
- }
- }
- }
- /method = method.toUpperCase();
- // // get 请求 把数据拼接在地址身上
- if(method == 'GET') {
- // // 建立连接
- xhr.open(method, url + '?' + data, flag);
- // // 发出请求
- xhr.send();
- // // post 请求需要把数据放在请求体里面 不拼接地址
- }else if(method == 'POST') {
- // // 建立连接
- xhr.open(method, url, flag);
- // // 前端告诉后端 我的数据是什么格式的 key=value&key1=value1
- xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
- // // 传递数据 发出请求 i
- xhr.send(data);
- // }
- // }
来源: http://www.bubuko.com/infodetail-3122971.html