通过PHP访问JSON对象
我有以下代码通过PHP访问JSON对象,php,javascript,jquery,json,Php,Javascript,Jquery,Json,我有以下代码 if (config.sendResultsURL !== null) { console.log("Send Results"); var collate =[]; for (r=0;r<userAnswers.length;r++) { collate.push('{"questionNumber'+parseInt(r+1)+ '"' + ': [{"UserAnswer":"'+userAnswers[r]+
if (config.sendResultsURL !== null)
{
console.log("Send Results");
var collate =[];
for (r=0;r<userAnswers.length;r++)
{
collate.push('{"questionNumber'+parseInt(r+1)+ '"' + ': [{"UserAnswer":"'+userAnswers[r]+'", "actualAnswer":"'+answers[r]+'"}]}');
}
$.ajax({
type: 'POST',
url: config.sendResultsURL,
data: '[' + collate.join(",") + ']',
complete: function()
{
console.log("Results sent");
}
});
}
从这里脚本将数据发送到emailData.php,该文件读取
$json = json_decode($_POST, TRUE);
$body = "$json";
$to = "myemail@email.com";
$email = 'Diesel John';
$subject = 'Results';
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Send the email:
$sendMail = mail($to, $subject, $body, $headers);
现在我确实收到了电子邮件,但是它是空白的
我的问题是如何将数据传递到emailData.php并从那里访问它?如果您解码json,您将得到一个哈希而不是一个字符串。如果您希望收到与控制台上打印内容相同的邮件,只需执行以下操作:
$body=$\u POST['data']代码>
另一个选项是将json解析为php哈希和var_转储,其中:
$json = json_decode($_POST['data'], TRUE);
$body = var_export($json, TRUE);
json_解码将字符串转换为对象。
只需执行以下代码并检查值
print_r($json)
直接将json对象分配给字符串这是非常糟糕的
创建要传递给PHP的对象
使用JSON.stringify()
为该对象生成JSON字符串
使用POST或GET并使用名称将其传递给PHP脚本
根据您的请求,从$\u GET['name']
或$\u POST['name']
捕获它
在php中应用json\u decode
,将json作为本机对象
在您的情况下,您只需传递userAnswers[r]和answers[r]。保留数组序列
在循环使用中
collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});
在ajax请求使用中
data: {"data" : JSON.stringify(collate)}
最后,
$json = json_decode($_POST['data'], TRUE); // the result will be an array.
使用下面的JavaScript代码
var collate =[], key, value;
for (r=0;r<userAnswers.length;r++) {
key = questionNumber + parseInt(r+1);
value = { "UserAnswer": userAnswers[r], "actualAnswer": answers[r] };
collate.push({ key : value });
}
$.post( config.sendResultsURL, { data: collate }, function(data) {
console.log("Results sent");
});
您将拥有阵列中的所有数据。此链接将帮助您找到解决方案:我真希望它能找到!我就是不明白!也许我盯着这个看太久了!您的建议将响应$json结构。只有使用输出缓冲才能捕捉到这一点。而且“$json”在PHP中也不是“非常糟糕”$json没有被解释或任何东西。当$json是一个数组/对象时,它是毫无意义的(在大多数情况下),但它并不坏;因为$json是对象而不是字符串。你是对的!我的观点是,将此称为“非常糟糕”有点夸张。我尝试了此操作,发送的电子邮件仅包含“1”,但我可以在控制台的“响应”选项卡中看到数组。我尝试了此操作,但发送的电子邮件包含“Null”,请尝试将我的答案与Shiplu的答案结合起来!
$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));
$data = json_decode( $_POST['data'], true );
$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));