我有一个项目,必须发送带有考试名称和从列表中选择的问题数量的考试数据:
上面是我必须遵循的项目体系结构
为了进行测试,backend.php只是发送它收到的JSON。但看起来它什么也没收到。
var audit_json = {“操作”:“考试创建”,“考试名称”:“测试- 1“,” questions [2,5,9]}
var str_json = "exam="+(JSON.stringify(exam_json));
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "functions.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(str_json);
make_test.php中的CURL:
<?php
$json = $_POST["exam"];
$exam_json = json_encode($json);
//if I echo $exam_json, it will display correctly meaning I am getting data here
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL =>"backend.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_POSTFIELDS => $exam_json,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($exam_json)),
);
curl_setopt_array($ch, $curlConfig);
$result_back = curl_exec($ch);
echo $result_back;
?>
backend.php接收通过CURL从make_exam.php发送的数据:
<?php
$data_test = json_decode(file_get_contents('php://input'), true);
echo $data_test;
//the echo is always empty
?>
答案 0 :(得分:0)
方法1:
对于HTTP正文中的json发布,您必须使用stipslash
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url ,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\n\t\"a\":1,\n\t\"b\":5\n}",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
方法2:
方法3:
使用Guzzle
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']
]);