/** * 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){varxmlhttp;if(window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=newXMLHttpRequest();}else{// code for IE6, IE5xmlhttp=newActiveXObject("Microsoft.XMLHTTP");}xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4){if(xmlhttp.status==200)callback(xmlhttp.responseText,url);elsefailCallback(url);}};xmlhttp.open("POST",url,true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");varkvpairs='';for(varkeyinkeyValuePairs){if(kvpairs=='')kvpairs=encodeURIComponent(key)+'='+encodeURIComponent(keyValuePairs[key]);elsekvpairs=kvpairs+'&'+encodeURIComponent(key)+'='+encodeURIComponent(keyValuePairs[key]);}xmlhttp.send(kvpairs);};
varurl='/demo/post';varkeyValuePairs={'name':'Bob','age':'21'};varcallback=function(responseText,url){// write your own handler for success of HTTP POSTalert('responseText from url '+url+':\n'+responseText);};varfailCallback=function(url){// write your own handler for failure of HTTP POSTalert('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].