http.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. function httpAjax(options){
  2. options = options ||{}; //调用函数时如果options没有指定,就给它赋值{},一个空的Object
  3. options.type=(options.type || "GET").toUpperCase();/// 请求格式GET、POST,默认为GET
  4. options.dataType=options.dataType || "json"; //响应数据格式,默认json
  5. var params=formatParams(options.data);//options.data请求的数据
  6. var xhr;
  7. //考虑兼容性
  8. if(window.XMLHttpRequest){
  9. xhr=new XMLHttpRequest();
  10. }else if(window.ActiveObject){//兼容IE6以下版本
  11. xhr=new ActiveXobject('Microsoft.XMLHTTP');
  12. }
  13. //启动并发送一个请求
  14. if(options.type=="GET"){
  15. xhr.open("GET",options.url+"?"+params,true);
  16. xhr.send(null);
  17. }else if(options.type=="POST"){
  18. xhr.open("post",options.url,true);
  19. //设置表单提交时的内容类型
  20. //Content-type数据请求的格式
  21. xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  22. xhr.send(params);
  23. }
  24. // 设置有效时间
  25. setTimeout(function(){
  26. if(xhr.readySate!=4){
  27. xhr.abort();
  28. }
  29. },options.timeout)
  30. // 接收
  31. // options.success成功之后的回调函数 options.error失败后的回调函数
  32. //xhr.responseText,xhr.responseXML 获得字符串形式的响应数据或者XML形式的响应数据
  33. xhr.onreadystatechange=function(){
  34. if(xhr.readyState==4){
  35. var status=xhr.status;
  36. if(status>=200&& status<300 || status==304){
  37. options.success&&options.success(xhr.responseText,xhr.responseXML);
  38. }else{
  39. options.error&&options.error(status);
  40. }
  41. }
  42. }
  43. }
  44. //格式化请求参数
  45. function formatParams(data){
  46. var arr=[];
  47. for(var name in data){
  48. arr.push(encodeURIComponent(name)+"="+encodeURIComponent(data[name]));
  49. }
  50. arr.push(("v="+Math.random()).replace(".",""));
  51. return arr.join("&");
  52. }