我最近才开始接触 PHP/AJAX/jQuery,在我看来这些技术的一个重要部分是 POST
和 GET
。
首先,POST
和GET
有什么区别?通过实验,我知道 GET
将返回变量及其值附加到 URL 字符串
website.example/directory/index.php?name=YourName&bday=YourBday
但是 POST
没有。
那么,这是唯一的区别,还是存在使用其中一种或另一种的特定规则或约定?
其次,我还在 PHP 之外看到了 POST
和 GET
:也在 AJAX 和 jQuery 中。 POST
和 GET
这 3 个之间有何不同?它们是否具有相同的想法、相同的功能,只是使用方式不同?
GET
和 POST
是两种不同类型的 HTTP 请求。
根据 Wikipedia :
GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.
和
POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.
所以本质上,GET
用于检索远程数据,而 POST
用于插入/更新远程数据。
HTTP/1.1 规范 (RFC 2616) 第 9 节
Method Definitions包含有关
GET
和
POST
以及其他 HTTP 方法的更多信息,如果您有兴趣的话。
除了解释每种方法的预期用途外,该规范还提供了至少一个为什么 GET
应该只用于检索数据的实际原因:
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead
最后,将
GET
用于 AJAX 请求时的一个重要考虑因素是某些浏览器(尤其是 IE)将缓存
GET
请求的结果。因此,例如,如果您使用相同的
GET
请求进行轮询,您将始终得到相同的结果,即使您正在查询的数据正在服务器端更新。缓解此问题的一种方法是通过附加时间戳使每个请求的 URL 唯一。