【发布时间】:2018-10-04 23:51:57
【问题描述】:
我有一个项目,我必须发送带有考试名称和从列表中选择的问题数量的考试数据:
- 我必须通过 AJAX 将 JSON 发送到我的 make_exam.php 文件
- questions.php 文件通过 CURL 向 backend.php 发送数据
以上是我必须遵循的项目架构
-
为了测试,backend.php 只是发送它接收到的 JSON。但看起来它什么也没收到。
var Exam_json = {"action":"exam_created","exam_name":"test- 1","问题[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
?>
【问题讨论】:
-
假设您的代码是正确的,您将发布到
backguy.php,并且您显示的页面称为backend.php,因此将其中一个更改为另一个,它会起作用吗? -
注意你不需要
json_encode($json)因为$json已经是json文本了,直接传递就行了 -
虽然您发布到本地 php 脚本,但您应该使用 url 而不是像 CURLOPT_URL =>"backend.php" 这样的相对路径。尝试将其更改为 CURLOPT_URL =>"localhost/curlscript/backend.php",
-
谢谢@PatrickEvans。额外的 json_encode($json) 导致了问题。
标签: javascript php ajax curl