博客列表 >2020-05-26——ajax请求步骤与函数封装

2020-05-26——ajax请求步骤与函数封装

A 枕上人如玉、
A 枕上人如玉、原创
2020年05月26日 12:13:59875浏览

1、ajax请求步骤

  1. //创建 XMLHttpRequest 对象
  2. var xhr = new XMLHttpRequest();
  3. //兼容写法
  4. var xhr = null;
  5. if (window.XMLHttpRequest)
  6. {
  7. // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
  8. xhr=new XMLHttpRequest();
  9. }
  10. else
  11. {
  12. // IE6, IE5 浏览器执行代码
  13. xhr=new ActiveXObject("Microsoft.XMLHTTP");
  14. }

 get请求方式

  1. //准备发送
  2. xhr.open("GET","url" + "userName=" + username,true); //请求方式,请求地址,是否异步(默认为true,异步请求)
  3. //执行发送
  4. xhr.send(null)

post请求方式

  1. //准备发送
  2. xmlhttp.open("POST","请求地址",true);
  3. //请求头
  4. xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  5. //参数
  6. var param = "userName=" + userName;
  7. //请求体 执行发送
  8. xmlhttp.send(param);
  1. //通过回调函数,获取数据
  2. xhr.onreadystatechange=function()
  3. {
  4. if (xhr.readyState==4 && xhr.status==200)
  5. {
  6. var result = xhr.responseText;
  7. }
  8. }

2、封装ajax函数

  1. function Ajax(type,url,params,dataType,callback){
  2. //创建 XMLHttpRequest 对象
  3. var xhr = new XMLHttpRequest();
  4. //准备发送
  5. if(type == "get"){
  6. if(params && params != ""){
  7. url = url + "?" + params;
  8. }
  9. }
  10. xhr.open(type,url,true);
  11. //执行发送
  12. if(type == "get"){
  13. xhr.send(null);
  14. }else if(type == "post"){
  15. xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
  16. xhr.send(params);
  17. }
  18. //通过回调函数,获取数据
  19. xhr.onreadystatechange=function()
  20. {
  21. if (xhr.readyState==4 && xhr.status==200)
  22. {
  23. var result = null;
  24. if(dataType == "json"){
  25. result = xhr.responseText; //返回字符串
  26. result = JSON.parse(result); //json格式化数据
  27. }else if(dataType == "xml"){
  28. result = xhr.responseXML;
  29. }else{
  30. result = xhr.responseText;
  31. }
  32. if(callback){
  33. callback(result);
  34. }
  35. }
  36. }
  37. }
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议