This post shows how to send data of HTML form in client browsers to
GAE Python server, and receive response data from the server. This technique
is common in the communication of client-server web applications.
<!doctype html><html><head><metacharset="utf-8"><title>AJAX HTML Form POST on Google App Engine Python example</title></head><body><formaction="javascript:ajaxformpost();"><inputid="input1"type="text"size='110'value="<example1>用 HashMap < Name, LinkedList < NameDistancePair > > 的 Java data structure 畫出此 directed weighted graph。</example1>"><br/><inputid="input2"type="text"size='110'value="<example2>用 HashMap < Name, LinkedList < NameDistancePair > > 的 Java data structure 畫出此 directed weighted graph。</example1>"><br/><inputtype="submit"value="Submit"></form><scriptsrc="post.js"></script></body></html>
Client side (JavaScript): Send form data to server by HTTP POST request.
Note that the data are encoded by JavaScriptencodeURIComponent() function
to send the data with special characters to servers robustly. ([4], [5], [6],
[7], [8])
/** * 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);};functionajaxformpost(){varkeyValuePairs={'input1':document.getElementById('input1').value,'input2':document.getElementById('input2').value};varcallback=function(responseText,url){alert('responseText from url '+url+':\n'+responseText);};varfailCallback=function(url){// write your own handler for failure of HTTP POSTalert('fail to post '+url);}HTTPPOST("/post",keyValuePairs,callback,failCallback);}
Server side (GAE Python): The data from client browsers are decoded by
urllib2.unquote() function. ([9], [10])