Ajax入门

什么是AJAX?

AJAX: 异步的Javascript和XML;

XMLHttpRequest对象

//现代浏览器内置XMLHttpRqueset对象;

//IE5 and IE6等用ActiveXObject("Microsoft.XMLHTTP")实现;

//兼容的XMLHttpRqueset对象:
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

请求

//规定请求类型、地址、是否异步
xmlhttp.open(method, url, async);
//method : get/post
//url : url
//async : true/false
//发送请求 xmlhttp.send(string);
//string : 仅用于post请求时

服务器响应

//responseText 获得字符串形式的响应数据
xmlhttp.responseText

//responseXML 获得XML形式的响应数据
xmlhttp.responseXML

onreadystatechange事件

//onreadystatechange 储存函数或函数名,readyState改变时触发

//readystate 储存XMLHttpRequest状态(0 - 4)
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求完成并且响应

//status 状态
成功:200
未找到页面:404

//当readyState == 4 && status == 200 表示响应已ok
xmlhttp.onreadystatechange = function(){
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
    //获得字符串形式的返回值,也可以获得XML形式的数据responseXML
    alert(xmlhttp.responseText)
  }
}

封装AJAX

function getAjax(method, url, fnCall, data){
    //创建兼容的XMLHttpRequest对象
    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    //规定发送形式、地址、异步
    xmlhttp.open(method, url, true);

    //发送
    if(method == "POST" || method == "post"){
        xmlhttp.send(data);
    }else{
        xmlhttp.send();
    }

    //成功
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            //获得字符串形式的返回值,也可以获得XML形式的数据responseXML
            fnCall(eval("("+xmlhttp.responseText+")"));
        }
    }
}

//
http://localhost/test.txt在本地服务器
getAjax("GET", "http://localhost/test.txt", function(msg){ alert(msg); });