Home >Backend Development >PHP Tutorial >Ajax small package get, post request

Ajax small package get, post request

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:08:20960browse
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==" var xml = xhr.responseXML;
  18. success(eval("("+xml+")")) ;
  19. } else if(ch=="["||ch=="{") {//json type
  20. txt = eval("("+txt+")");
  21. success(txt);
  22. } else {//If you don’t know, just return
  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 request
  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 type
  45. txt = eval("("+txt+")");
  46. success(txt);
  47. } else {//Don't know, return directly
  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. }
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