Javascript学习-Ajax

2017-03-23  本文已影响8人  yoyo鹿鸣

Ajax 异步更新页面信息

XMLHttpRequest API

利用js的内置对象XmlHttpRequest对象与后台通信得到数据后渲染页面

get代码:

var xhr= new XMLHttpRequest;
//设置请求
xhr.open('get','url');
xhr.send(null);
//接受服务器相应
xhr.onreadystatechange = function(){
  if(xhr.readtState==4){
        //处理请求       
  }
}

post代码:

var xhr= new XMLHttpRequest;
//设置请求
xhr.open('post','url');
//设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;');
//设置请求主题 post的数据
xhr.send('    ');

//接受服务器相应
xhr.onreadystatechange = function(){
  if(xhr.readtState==4){
        //处理请求       
  }
}
readtState由0-4五个值

分别对应了:
0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send()方法,正在发送请求
2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
3 - (交互)正在解析响应内容
4 - (完成)响应内容解析完成,可以在客户端调用了

get 与post区别
同步与异步

xhr.open('post','url',‘默认true’);
默认采用异步方式

上一篇 下一篇

猜你喜欢

热点阅读