function getXhr(){ var xhr = null; if(window.XMLHttpRequest){ //高版本浏览器 xhr = new XMLHttpRequest; }else{ //IE低版本浏览器 xhr = new ActiveXObject("Microsoft.XMLHttp"); } return xhr; } var xhr = getXhr();
open(method, url, async);
xhr.open('post', 'data_montor.php', true);
xhr.open('get', 'data_montor.php?user = name', true); //method 表示get/post //url 表示请求的地址 //async 表示同步仍是异步,async = true 异步(默认) //若将async设置为false,官方认为XMLHttpRequest就是实现异步交互的会进行警告
//若是是get方法请求参数应跟在url以后,而不是经过send发送
send(请求参数)方法 //请求参数的格式 key = value xhr.send('user = xinyue') //注意:若是使用get方法,send不能向服务器发送请求数据,可是也不能忽略 //须要写成 send(NULL); 而后请求数据应放在open方法中的Url以后 //(详见上一步)
xhr . onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr. status == 200){ var data = xhr.responseText; //HTML格式使用responseText接收服务器端的相应数据,解析过程比较复杂(拆串),拆串拼串极易出错 console.log(data); } } }
readyState 得服务器端当前通讯状态 :
0 服务器端还没有初始化
1 正在发送请求
2 请求完成
3 请求成功,客户端正在接收服务器端的数据
4 响应完成
status : 1XX 信息类
2XX 成功
3XX 重定向
4XX 客户端错误
5XX 服务器端错误
php