如何从 HTML 表单发送 JSON 请求并在 PHP 中接收


How to send JSON request from HTML form and receive in PHP

我使用带有多个字段的HTML表单。但是我需要将选择字段(下拉列表)中的值转换为php aray。我的表单包含以下字段:

City - Text
IN - Text/Date
OUT - Text/Date
Rooms - Select ( 1->5 )
Adults - Select ( 1->5 )
Childs - Select ( 0->5 )

我需要接收的 php 数组是

Example If Rooms is - 1 and Adults - 2 the response must be:
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult")); 
Example If Rooms is - 2 and Adults - 3 the response must be:
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult")); 
$rooms[] = array(array("paxType" => "Adult")); 

我正在使用以下代码

$Adults = intval($_POST["Adults"]);
$rooms = array();
for ($x = 0; $x < $Adults; $x++) {
    array_push($rooms,array("paxType" => "Adult"));
}

但我收到了 1 间客房和 1 名成人的回复。

即使使用纯HTML表单提交也很容易做到这一点(也可以使用JSON XHR请求完成)

我假设您的SELECT HTML 表单元素名称是 "adultCount"

$adultCount = intval($_GET["adultCount"]);
$rooms = array();
for ($x = 0; $x < $adultCount; $x++) {
    array_push($rooms,array("paxType" => "Adult"));
} 

仅供参考,我们不对网页使用 SOAP,即使它可以完成(这是不必要的)。