1

[JavaScipt] Cross-Browser HTTP POST Request

 2 years ago
source link: http://siongui.github.io/2012/10/05/javascript-http-post-request/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[JavaScipt] Cross-Browser HTTP POST Request

Updated: March 02, 2015

This post shows how to make HTTP POST request with query string (key-value pairs) in cross-browser way. The following HTTPPOST function demonstrates how to make such AJAX request:

post.js | repository | view raw

/**
 * Cross-browser HTTP POST request
 * @param {string} url The url of HTTP POST request
 * @param {object} keyValuePairs The object which contains data of key-value
 *                 pair(s) to be POSTed. For example, object {'name': 'Bob',
 *                 'age': '21'} represents "name=Bob&age=21".
 * @param {function} callback The callback function if HTTP POST succeeds
 * @param {function} failCallback The callback function if HTTP POST fails
 */
HTTPPOST = function(url, keyValuePairs, callback, failCallback) {
  var xmlhttp;

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200)
        callback(xmlhttp.responseText, url);
      else
        failCallback(url);
    }
  };

  xmlhttp.open("POST", url, true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  var kvpairs = '';
  for (var key in keyValuePairs) {
    if (kvpairs == '')
      kvpairs = encodeURIComponent(key) + '=' +
                encodeURIComponent(keyValuePairs[key]);
    else
      kvpairs = kvpairs + '&' + encodeURIComponent(key) + '=' +
                encodeURIComponent(keyValuePairs[key]);
  }

  xmlhttp.send(kvpairs);
};

Usage

usage.js | repository | view raw

var url = '/demo/post';
var keyValuePairs = {'name': 'Bob', 'age': '21'};

var callback = function(responseText, url) {
  // write your own handler for success of HTTP POST
  alert('responseText from url ' + url + ':\n'
        + responseText);
};

var failCallback = function(url) {
  // write your own handler for failure of HTTP POST
  alert('fail to post ' + url);
};

HTTPPOST(url, keyValuePairs, callback, failCallback);

Note that you can only make requests in the same domain. To make cross-domain requests, please see reference [1] for more detail. To make cross-browser HTTP GET request, please see reference [2]. To make HTTP POST requests to GAE Python server, see reference [3].


References:

[4]XMLHttpRequest - Web API Interfaces | MDN


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK