简体   繁体   English

通过PHP访问JSON对象

[英]Accessing JSON object via PHP

I have the following code.. 我有以下代码..

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");
    }
  });
}

Using Firebug I get this from the console. 使用Firebug我从控制台获取此信息。

[{"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"}]}]

From here the script sends data to emailData.php which reads... 从这里脚本将数据发送到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);

Now I do get the email however it is blank. 现在我收到了电子邮件,但它是空白的。

My question is how do I pass the data to emailData.php and from there access it? 我的问题是如何将数据传递给emailData.php并从那里访问它?

  1. Create an object that you want to pass to PHP 创建要传递给PHP的对象
  2. Use JSON.stringify() to make a JSON string for that object. 使用JSON.stringify()为该对象创建JSON字符串。
  3. Pass it to PHP script using POST or GET and with a name . 使用POST或GET并使用名称将其传递给PHP脚本。
  4. Depending on your request capture it from $_GET['name'] OR $_POST['name'] . 根据您的请求从$_GET['name'] OR $_POST['name']
  5. Apply json_decode in php to get the JSON as native object. 在php中应用json_decode以将JSON作为本机对象。

In your case you can just pass userAnswers[r] and answers[r]. 在你的情况下,你可以传递userAnswers [r]和答案[r]。 Array sequence are preserved. 数组序列被保留。

In for loop use, 在for循环使用中,

collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});

In ajax request use, 在ajax请求中使用,

data: {"data" : JSON.stringify(collate)}

In the PHP end, 在PHP端,

 $json = json_decode($_POST['data'], TRUE); // the result will be an array.
$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));

If you decode your json, you will have a hash and not a string. 如果你解码你的json,你将有一个哈希而不是一个字符串。 If you want to be mailed the same as what you printed on the console, simply do this: 如果您希望邮寄的内容与您在控制台上打印的内容相同,只需执行以下操作:

$body = $_POST['data'];

Another option would be to parse json into a php hash and var_dump that: 另一个选择是将json解析为php哈希和var_dump:

$json = json_decode($_POST['data'], TRUE);
$body = var_export($json, TRUE);

json_decode converting string to object. json_decode将字符串转换为对象。 just do bellow code and check the values. 只需执行以下代码并检查值。

print_r($json) 

Directly assign json object to string this is very bad. 直接将json对象分配给字符串这是非常糟糕的。

Using below JavaScript code 使用下面的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"); 
});

And do this in PHP 并在PHP中执行此操作

$data = json_decode( $_POST['data'], true );

and you will have all your data with array. 并且您将拥有数组的所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM