>  기사  >  백엔드 개발  >  Ajax的小封装 get,post请求

Ajax的小封装 get,post请求

WBOY
WBOY원래의
2016-07-25 09:08:20796검색
Ajax的小封装对ajax的get请求的小封装
  1. function Ajax() {
  2. var xhr =null;
  3. if(window.XMLHttpRequest) {
  4. xhr = new XMLHttpRequest();
  5. } else {
  6. xhr = new ActiveXObject("Microsoft.XMLHttp");
  7. }
  8. this.get=function(url,success,fail){ //get请求
  9. xhr.open("GET", "1.jsp",true);
  10. xhr.onreadystatechange=function(){
  11. if(xhr.readyState==4) {
  12. alert(xhr.status);
  13. if(xhr.status==200) {
  14. var txt = xhr.responseText;
  15. txt = eval("("+txt+")");
  16. var ch = txt.charAt(0);
  17. if(ch==" var xml = xhr.responseXML;
  18. success(eval("("+xml+")"));
  19. } else if(ch=="["||ch=="{") {//json类型
  20. txt = eval("("+txt+")");
  21. success(txt);
  22. } else {//不知道直接返回
  23. success(txt);
  24. }
  25. } else {
  26. if(fail) {
  27. fail(xhr.status);
  28. }
  29. }
  30. }
  31. };
  32. xhr.send(null);
  33. };
  34. this.post = function (url,param,success,fail) {//post请求
  35. xhr.open("POST", "1.jsp",true);
  36. xhr.onreadystatechange=function(){
  37. if(xhr.readyState==4) {
  38. alert(xhr.status);
  39. if(xhr.status==200) {
  40. var txt = xhr.responseText;
  41. var ch = txt.charAt(0);
  42. if(ch==" var xml = xhr.responseXML;
  43. success(eval("("+xml+")"));
  44. } else if(ch=="["||ch=="{") {//json类型
  45. txt = eval("("+txt+")");
  46. success(txt);
  47. } else {//不知道直接返回
  48. success(txt);
  49. }
  50. } else {
  51. if(fail) {
  52. fail(xhr.status);
  53. }
  54. }
  55. }
  56. };
  57. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  58. xhr.send(param);
  59. };
  60. }
复制代码


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:BLOG搬家迁移 다음 기사:php实现简单的日历类