Posted By

Piotrek290 on 04/02/10


Tagged

ajax javascript class request


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

wirenaught


Simple Ajax Class


 / Published in: JavaScript
 

  1. // Request class
  2. Request = function(){
  3. Request = window.XMLHttpRequest?new XMLHttpRequest():window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):false;
  4. Request.fn = function(fn){
  5. if(typeof fn=='string')return new Function(fn);
  6. if(typeof fn=='function')return fn;
  7. if(typeof fn=='undefined')return new Function();
  8. };
  9. Request.config = {
  10. 'xml' : false,
  11. '404' : 'File not found'
  12. };
  13.  
  14. Request.success = false;
  15. Request.loading = false;
  16. Request.error = false;
  17.  
  18. Request.submit = function(obj){
  19. if(Request){
  20. Request.onreadystatechange = function(){
  21. if(Request.status==200){
  22. if(Request.readyState==4){
  23. Response = Request.config['xml']?Request.responseXml:Request.responseText;
  24. if(Request.success){
  25. Request.fn(Request.success).call(this, Response, Request);
  26. } else {
  27. Request.fn(obj.success).call(this, Response, Request);
  28. }
  29. } else {
  30. if(Request.success){
  31. Request.fn(Request.loading).call(this, Request);
  32. } else {
  33. Request.fn(obj.loading).call(this, Request);
  34. }
  35. }
  36. } else {
  37. if(Request.success){
  38. Request.fn(Request.error).call(this, Request.config['404']);
  39. } else {
  40. Request.fn(obj.error).call(this, Request.config['404']);
  41. }
  42. };
  43. }
  44.  
  45. Request.open("GET", obj.url, true);
  46. Request.send(null);
  47. } else obj.error.call(this, Request);
  48. };
  49.  
  50. return Request;
  51. };
  52.  
  53. // Eval code
  54. var req = new Request;
  55. req.submit({
  56. url : 'plik.xml',
  57. xml : false,
  58. success : function(res, req){
  59. document.getElementById('p2').innerHTML = res;
  60. },
  61. loading : function(){ console.log('loading...'); },
  62. error : function(err){ console.log(err); }
  63. });

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: danteq on September 3, 2010

this script have errors in internet explorer but if changue this lines: if(Request.status==200){ if(Request.readyState==4){

to:

if(Request.readyState==4){ if((Request.status==200)||(Request.status==0)){

that workin in all web browsers but y have and error when I try execute loading : function(){ console.log('loading...'); }, error : function(err){ console.log(err); }

that function not working dont do anything

You need to login to post a comment.