本文介绍了通过PHP访问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]+'", "actualAnswer":"'+answers[r]+'"}]}');
}
$.ajax({
type: 'POST',
url: config.sendResultsURL,
data: '[' + collate.join(",") + ']',
complete: function()
{
console.log("Results sent");
}
});
}
使用Firebug,我可以从控制台获得此信息.
Using Firebug I get this from the console.
[{"questionNumber1": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber2": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber3": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber4": [{"UserAnswer":"3", "actualAnswer":"1"}]},{"questionNumber5": [{"UserAnswer":"3", "actualAnswer":"1"}]}]
脚本从此处将数据发送到emailData.php,其内容为...
From here the script sends data to emailData.php which reads...
$json = json_decode($_POST, TRUE);
$body = "$json";
$to = "[email protected]";
$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);
现在我收到了电子邮件,但是它为空.
Now I do get the email however it is blank.
我的问题是如何将数据传递到emailData.php并从那里访问它?
My question is how do I pass the data to emailData.php and from there access it?
推荐答案
- 创建要传递给PHP的对象
- 使用
JSON.stringify()
为该对象创建JSON字符串. - 使用POST或GET并使用名称将其传递到PHP脚本.
- 根据您的请求从
$_GET['name']
或$_POST['name']
捕获它. - 在php中应用
json_decode
以获取JSON作为本机对象.
- Create an object that you want to pass to PHP
- Use
JSON.stringify()
to make a JSON string for that object. - Pass it to PHP script using POST or GET and with a name.
- Depending on your request capture it from
$_GET['name']
OR$_POST['name']
. - Apply
json_decode
in php to get the JSON as native object.
在您的情况下,您可以只传递userAnswers [r]和答案[r].数组序列被保留.
In your case you can just pass userAnswers[r] and answers[r]. Array sequence are preserved.
在循环使用中,
collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});
在ajax请求使用中,
In ajax request use,
data: {"data" : JSON.stringify(collate)}
在PHP端,
$json = json_decode($_POST['data'], TRUE); // the result will be an array.
这篇关于通过PHP访问JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!