HTTP Request

HTTP Request


Published in: JavaScript 


Generic global code for managing XMLHttpRequest objects.

 
  
  1. // ----------------------------------------
  2. // Wrapper function for constructing a request object.
  3. // Parameters:
  4. // reqType: The HTTP request type, such as GET or POST.
  5. // url: The URL of the server program.
  6. // asynch: Whether to send the request asynchronously or not.
  7. // ----------------------------------------
  8.  
  9. function httpRequest (reqType ,url ,asynch )  {
  10.  
  11. // Mozilla-based browsers
  12. if  (window. XMLHttpRequest )  {
  13. request  =  new XMLHttpRequest ( );
  14. }  else  if  (window. ActiveXObject )  {
  15. request  =  new ActiveXObject ( "Msxml2.XMLHTTP" );
  16. if  ( !request )  {
  17. request  =  new ActiveXObject ( "Microsoft.XMLHTTP" );
  18. }
  19. }
  20.  
  21. // Request could still be null if neither ActiveXObject
  22. // initialization succeeded
  23. if  (request )  {
  24. // If the reqType param is POST, then the fifth arg is the POSTed data
  25. if  (reqType. toLowerCase ( )  !=  "post" )  {
  26. initReq (reqType , url , asynch , respHandle );
  27. }  else  {
  28. // The POSTed data
  29. var args  = arguments [ 4 ];
  30. if  (args  !=  null  && args. length  > 0 )  {
  31. initReq (reqType , url , asynch , respHandle , args );
  32. }
  33. }
  34. }  else  {
  35. alert ( "Your browser does not permit the use of all "  +
  36. "of this application's features!" );
  37. }
  38.  
  39. }
  40.  
  41. // ----------------------------------------
  42. // Initialize a request object that is already constructed
  43. // ----------------------------------------
  44.  
  45. function initReq (reqType , url , bool , respHandle )  {
  46. try  {
  47. // Specify the function that will handle the HTTP response
  48. request. onreadystatechange  = handleResponse;
  49. request. open (reqType , url , bool );
  50. // If the reqType param is POST, then the
  51. // fifth argument to the function is the POSTed data
  52. if  (reqType. toLowerCase ( )  ==  "post" )  {
  53. // Set the Content-Type header for a POST request
  54. request. setRequestHeader ( "Content-Type" ,  "application/x-ww-form-urlencoded; charset=UTF-8" );
  55. request. send (arguments [ 4 ] );
  56. }  else  {
  57. request. send ( null );
  58. }
  59. }  catch  (errv )  {
  60. alert ( "The application cannot contact the server at the moment. "  +
  61. "Please try again in a few seconds.\n"  +
  62. "Error detail: " errv. message );
  63. }
  64. }

你可能感兴趣的:(request)