XMLhttp笔记

一.创建对象:

var xhr=new XMLHttpRequest;(new ActiveXObject("Microsoft.XMLHTTP");)

二.发送请求:

xhr.open(method,url,async);//mothod为POST或GET请求,async默认为true(异步)

xhr.send(string)//get方法时string为null,POST方法是传输数据;

三。监听请求变化,获得返回数据:

xhr.onreadystatechange=function(){//readyState属性改变时,触发onreadystatechange事件

  if(xhr.readyState==4&xhr.status==200{

    alert(xhr.responseText)//xhr.responseText返回字符串xhr.responseXML返回XML格式数据

  }else{

    alert(xhr.statusText)

  }

}  

五.xhr二级变化

1.xhr对象增加了timeout属性,设置HTTP请求时限: xhr.timeout = 3000;

与之配套的的timeout事件,用来指定回调函数:

  xhr.ontimeout = function(event){

    alert('请求超时!');

  }

2.fromData对象:模拟表单

建立对象:var formData = new FormData();

添加表单项:

  formData.append('username', '张三');
  formData.append('id', 123456);

传输:xhr.send(formData);//与用表单提交一样

也可以获取文档表单对象:

  var form = document.getElementById('myform');
  var formData = new FormData(form);
  formData.append('secret', '123456'); // 添加一个表单项
  xhr.open('POST', form.action);
  xhr.send(formData);

上传文件:

  var formData = new FormData();

  for (var i = 0; i < files.length;i++) {

    formData.append('files[]', files[i]);

  }

posted on 2017-04-02 00:59  周裕涛  阅读(167)  评论(0编辑  收藏  举报

导航