Blogger Information
Blog 12
fans 0
comment 0
visits 8905
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
2020-05-26——ajax请求步骤与函数封装
A 枕上人如玉、
Original
888 people have browsed it

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. }
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post