Home  >  Article  >  Backend Development  >  Ajax small package get, post request

Ajax small package get, post request

WBOY
WBOYOriginal
2016-07-25 09:08:20796browse
Ajax small encapsulation A small encapsulation of ajax get request
  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 request
  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=="<") { //xml type
  18. var xml = xhr.responseXML;
  19. success(eval("("+xml+")")) ;
  20. } else if(ch=="["||ch=="{") {//json type
  21. txt = eval("("+txt+")");
  22. success(txt);
  23. } else {//If you don’t know, just return
  24. success(txt);
  25. }
  26. } else {
  27. if(fail) {
  28. fail(xhr.status);
  29. }
  30. }
  31. }
  32. };
  33. xhr.send(null );
  34. };
  35. this.post = function (url,param,success,fail) {//post request
  36. xhr.open("POST", "1.jsp",true);
  37. xhr.onreadystatechange =function(){
  38. if(xhr.readyState==4) {
  39. alert(xhr.status);
  40. if(xhr.status==200) {
  41. var txt = xhr.responseText;
  42. var ch = txt.charAt (0);
  43. if(ch=="<") { //xml type
  44. var xml = xhr.responseXML;
  45. success(eval("("+xml+")"));
  46. } else if(ch ==="["||ch=="{") {//json type
  47. txt = eval("("+txt+")");
  48. success(txt);
  49. } else {//Don't know, return directly
  50. success(txt);
  51. }
  52. } else {
  53. if(fail) {
  54. fail(xhr.status);
  55. }
  56. }
  57. }
  58. };
  59. xhr.setRequestHeader("Content-Type", " application/x-www-form-urlencoded");
  60. xhr.send(param);
  61. };
  62. }
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn