又是一個朋友的問題,他有一個form,method是get,action里面帶了參數,例如:
<form action="test.do?p1=1" method="GET">
<input type="text" size="10" value="2" name="p2">
<input type=submit value="Submit">
</form>
在服務器端,提交以后的信息里面參數p1的值沒有了!
如果把method修改為POST方式就沒有問題了;又或者把form里面的那個input輸入框去掉,那么p1也有值了。
很奇怪吧。
目前還不清楚是瀏覽器導致這種問題還是有規范約定這種處理方式。我的感覺是有規范進行這種約定,然后瀏覽器就把form的內容轉換為一個URL,例如例子的情況,瀏覽器就把請求的 URL轉換為test.do?p2=2了,忽略了action原先帶的參數p1.而如果是POST方式,那么瀏覽器就不用做轉換,直接提交了。
沒有辦法,我們只能接受這個事實。
所以如果你的參數很多,有很多是動態的,需要用戶輸入的,那么很簡單,用POST方式吧。其實絕大多數form都是應該使用POST的。GET方式一般都是在使用鏈接的時候所使用的方式。
另外提醒一點的是,GET方式下URL的長度是有限制的,好像是1024個字符。另外GET的設計初衷應該是每次請求的返回結果都是相同的,而POST是用于對服務器進行更新操作。
看到一個講解這個問題很詳細的英文文章,有興趣的自己看看:Methods GET and POST in Html forms - what‘s the difference?
其中的一段我感覺大家很有必要清楚:
When users revisit a page that resulted from a form submission, they might be PResented with the page from their history stack (which they had probably intended), or they might be told that the page has now eXPired. Typical user response to the latter is to hit Reload.
This is harmless if the request is idempotent, which the form author signals to the browser by specifying the GET method.
Browsers typically will (indeed "should") caution their users if they are about to resubmit a POST request, in the belief that this is going to cause a further "permanent change in the state of the universe", e.g. ordering another Mercedes-Benz against their credit card or whatever. If users get so accustomed to this happening when they try to reload a harmless idempotent request, then sooner or later it‘s going to bite them when they casually [OK] the request and do, indeed, order a second pizza, or invalidate their previous competition entry by apparently trying to enter twice, or whatever.
大意就是如果用戶查看一個form提交的結果頁面,GET方式和POST方式就是告訴瀏覽器是可以從緩存里面取還是不能從緩存里面取。如果是POST方式,那么應該是重新加載的,不應該從緩存取。如果用戶重復提交一個POST方式的form,那么瀏覽器應該警告用戶,因為這個會造成服務器狀態的永久變化(例如用你的信用卡重復預定一個匹薩),如果是GET方式,那么瀏覽器不應該警告用戶。
(出處:http://m.survivalescaperooms.com)
新聞熱點
疑難解答