解惑

解己之惑,解人之惑

Post和Get

又是一个朋友的问题,他有一个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方式,那么浏览器不应该警告用户。

(Visited 168 times, 1 visits today)

1 Comment

发表评论

邮箱地址不会被公开。 必填项已用*标注

© 2024 解惑

本主题由Anders Noren提供向上 ↑