PHP 中的 JSON 格式不正确,无法从 JQuery Ajax 请求中格式化


JSON in PHP not correctly formatted from an JQuery Ajax request

我有一个JQuery AJAX请求将一些JSON数据发送到PHP脚本,但是,当涉及到操作数据甚至尝试访问它时,它的行为就像一个字符串,但我需要它表现得像一个关联数组。

JavaScript

var all_data = [];
$.each($("[id*=card]"), function(i, value) {
  var name_a = $(value).find('#story_name_div').text();
  var text_a = $(value).find('#story_text_div').text();
  var point_a = $(value).find('#story_point_div').text();
  var phase_a = $(value).find('#story_phase').val();
  var date_a = $(value).find('#story_date').val();
  var author_a = $(value).find('#username_div').text();
var story_data = {
  "name": name_a ,
  "text": text_a ,
  "point": point_a ,
  "data": phase_a ,
  "date": date_a ,
  "author": author_a 
};
all_data.push(story_data);
});
$.ajax({
   url: 'save_server_script.php',
   type: 'POST',
   processData:false,
   dataType: "json",
   data: "json=" + JSON.stringify(all_data),
   success: function(res){
   var json_a = $.parseJSON(res);
   console.log(json_a);
   },
   error: function(err){
   console.log("error");
   }
});

创建的 JSON

[json] => [{"name":"jhb","text":"gjh","point":"jhv","phase":"planning","date":"21/9/2013 - 4:23:16","author":"Created by - ljhlkjhb"}]

.PHP

print_r($_POST); // prints out entire JSON
print($_POST["json"][0]["story_name"]);
// Warning : Illegal string offset 'story_name' in C:'xampp'htdocs'save_server_script.php on line 15
print($_POST["json"][0]); // prints out a '['
foreach($_POST["json"] as $hello) { // invalid argument supplied for foreach
    print $hello["story_name"];
}

我也尝试过通过PHP解码,但无济于事。

尝试

$json = json_decode($_POST['json']);
echo $json[0]->author;

在您的代码段中,您指的是 story_name ,但这不是 JSON 字符串中的元素。

你必须先在 php 中将 json 解码为数组:

$arr = json_decode($_POST["json"]);
 //now you can use foreach on the array it returned
foreach($arr as $key => $value){
   //now you can use $value["text"] , $value["author"] etc
}

php 接收的数据是 json 格式,需要转换为数组格式才能在其上使用 foreach。PS 您的 json 数据中没有"story_name"。