HTTP請求中,如果是get請求,那麼表單參數以name=value&name1=value1的形式附到url的後面,如果是post請求,那麼表單參數是在請求體中,也是以name=value&name1=value1的形式在請求體中。通過chrome的開發人員工具可以看到如下(這裡是可讀的形式,不是真正的HTTP請求協議的請求格式):
get請求:
[plain] view plain copy RequestURL:http://127.0.0.1:8080/test/test.do?name=mikan&address=street Request Method:GET Status Code:200 OK Request Headers Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding:gzip,deflate,sdch Accept-Language:zh-CN,zh;q=0.8,en;q=0.6 AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2 Connection:keep-alive Cookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8D Host:127.0.0.1:8080 Referer:http://127.0.0.1:8080/test/index.jsp User-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36 Query String Parameters name:mikan address:street Response Headers Content-Length:2 Date:Sun, 11 May 2014 10:42:38 GMT Server:Apache-Coyote/1.1
Post請求:
[plain] view plain copy RequestURL:http://127.0.0.1:8080/test/test.do Request Method:POST Status Code:200 OK Request Headers Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding:gzip,deflate,sdch Accept-Language:zh-CN,zh;q=0.8,en;q=0.6 AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2 Cache-Control:max-age=0 Connection:keep-alive Content-Length:25 Content-Type:application/x-www-form-urlencoded Cookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8D Host:127.0.0.1:8080 Origin:http://127.0.0.1:8080 Referer:http://127.0.0.1:8080/test/index.jsp User-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36 Form Data name:mikan address:street Response Headers Content-Length:2 Date:Sun, 11 May 2014 11:05:33 GMT Server:Apache-Coyote/1.1
這裡要注意post請求的Content-Type為application/x-www-form-urlencoded,參數是在請求體中,即上面請求中的Form Data。
在servlet中,可以通過request.getParameter(name)的形式來擷取表單參數。
而如果使用原生AJAX POST請求的話:
[javascript] view plain copy function getXMLHttpRequest() { var xhr; if(window.ActiveXObject) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); }else if (window.XMLHttpRequest) {