×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Jing Tai Piao
Added: Oct 16, 2012 1:46 AM
Views: 57
Tags: no tags
post data in native javascript
  1. function sendRequest(url,callback,postData) {
  2.         var req = createXMLHTTPObject();
  3.         if (!req) return;
  4.         var method = (postData) ? "POST" : "GET";
  5.         req.open(method,url,true);
  6.         req.setRequestHeader('User-Agent','XMLHTTP/1.0');
  7.         if (postData)
  8.                 req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
  9.         req.onreadystatechange = function () {
  10.                 if (req.readyState != 4) return;
  11.                 if (req.status != 200 && req.status != 304) {
  12. //                      alert('HTTP error ' + req.status);
  13.                         return;
  14.                 }
  15.                 callback(req);
  16.         }
  17.         if (req.readyState == 4) return;
  18.         req.send(postData);
  19. }
  20.  
  21. var XMLHttpFactories = [
  22.         function () {return new XMLHttpRequest()},
  23.         function () {return new ActiveXObject("Msxml2.XMLHTTP")},
  24.         function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  25.         function () {return new ActiveXObject("Microsoft.XMLHTTP")}
  26. ];
  27.  
  28. function createXMLHTTPObject() {
  29.         var xmlhttp = false;
  30.         for (var i=0;i<XMLHttpFactories.length;i++) {
  31.                 try {
  32.                         xmlhttp = XMLHttpFactories[i]();
  33.                 }
  34.                 catch (e) {
  35.                         continue;
  36.                 }
  37.                 break;
  38.         }
  39.         return xmlhttp;
  40. }
  41. It's used like this:
  42.  
  43. sendRequest('file.txt',handleRequest);