了解 XMLHttpRequest 如何将数据发送到服务器


Understanding how XMLHttpRequest sends data to a server

我还没有完全理解到服务器的数据传输。我有哪些方法?当我开始学习PHP时,我认为有两种方法称为GET,它加密URL中的数据,POST以另一种方式将数据发送到服务器。不过,我不知道具体在哪里。

现在我想了解 RESTful 服务器后端,我了解到GETPOST只是请求方法,其中包括 PUTDELETE ,这似乎与数据传输到服务器的方式无关。

此外,我读到可以在 HTTP 标头中发送其他数据。这是POST实际发送数据的方式还是有区别?

我想使用 PHP 的 $_POST 数组读取 POST 数据,而不管请求方法如何,但这不起作用。另一方面,当我尝试从php://input手动解析标头信息时,我看不到 POST 数据。有人可以向我解释在不同情况下数据在哪里传输吗?

我的目标是从客户端获取参数,而不考虑内容类型(可能是form-datajson或其他内容)和请求方法。如何在 PHP 中执行此操作?请求将使用JQuery的AJAX功能发送。

解释 http 如何使用 nc 工作http://linux.die.net/man/1/nc

获取

$ nc -l 8888启动虚拟服务器,在 8888 处侦听

使用 jQuery 发送 GET 请求(impl 通过 XHR)

$.get("http://localhost:8888", { a :1 ,b: 2})

nc 会将 XHR 发送到服务器的内容打印到 stdout

$nc -l 8888
GET /?a=1&b=2&_=1383234919249 HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Accept: */*
Origin: http://stackoverflow.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
DNT: 1
Referer: http://stackoverflow.com/questions/19710815/understanding-how-xmlhttprequest-sends-data-to-a-server
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4

因此,PHP 将GET /?a=1&b=2&_=1383234919249解析为$_GET

发布

使用nc录制开机自检

POST / HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Content-Length: 7
Accept: */*
Origin: http://stackoverflow.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Content-Type: application/x-www-form-urlencoded
DNT: 1
Referer: http://stackoverflow.com/questions/19710815/understanding-how-xmlhttprequest-sends-data-to-a-server
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
a=1&b=2

在这里你可以看到Content-Type: application/x-www-form-urlencoded,它告诉浏览器发送的 http 正文是形式编码的

因此,PHP 解析a=1&b=2数组$_POST

为什么php://input看不到帖子正文

根据 http://php.net/manual/en/wrappers.php.php

php://input 是一个流,只能读取一次

以下是来自 PHP 文档

注意:使用 php://input 打开的流只能读取一次; 流不支持寻道操作。但是,根据 SAPI实现,也许可以打开另一个 php://input 流式传输并重新开始阅读。仅当请求正文时,才可以执行此操作 数据已保存。通常,POST 请求就是这种情况, 但不是其他请求方法,例如 PUT 或 PROPFIND。