我正在尝试使用Jquery将json文件传递给PHP。当我检查响应时,我得到错误json_decode期望参数1是一个字符串。
这是我的jquery例程
$("#ProcessData").click(function(){
var cols = $("#tblGroup thead tr th").map(function(){
return $(this).text(); });
var headers = cols;
// Fetch the data from the table body
var tableObject = $("#tblGroup tbody tr.tableClass").map(function(i){
var row = {}; $(this).find('td').each(function(i){
var rowName = headers[i];
row[rowName] = $(this).text();
});
return row;
}).get();
// convert object to JSON
JSON.stringify(tableObject);
//now call ajax to pass info to php
$.ajax({
url: 'php/ProcessOrder.php',
data: {my_json_data: tableObject},
type: 'POST',
async: false,
dataType: 'json', cache:false
});
});
这是我的PHP脚本
<?PHP
//this is the layout of the json object
//Title:First Name:Surname:Group Name this will needamending as the json object builds
require("dbsettings.php");
$_Reference= $_POST["my_json_data"]; //this is a json object
// Loop through Array
$someArray = json_decode($_Reference, true); // Replace ... with your PHP Array
foreach ($someArray as $key => $value) {
echo $value["Title"] . ", " . $value["First Name"] . ", " . $value["Surname"] . ", " . $value["Group Name"] . "<br>";
}
?>
这是我的json对象
{"Title":"Mr","First Name":"12","Surname":"12","Group Name":"as"}
使用php小提琴我创建并测试了这个完美运行的脚本
<?php
$someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
// Loop through Array
$someArray = json_decode($someJSON, true); // Replace ... with your PHP Array
foreach ($someArray as $key => $value) {
echo $value["name"] . ", " . $value["gender"] . "<br>";
}
?>
我注意到的一件事是我的php fidle json文件有[]发布的对象不是这个错误消息引用的吗?或者我不应该JSON.stringfy()并将其作为字符串传递给php并使用JSON_encode? p>
感谢您的帮助
答案 0 :(得分:0)
JSON.stringify
返回编码的字符串。您必须发布其返回的值,而不是传递给它的参数。
// convert object to JSON
json = JSON.stringify(tableObject);
//now call ajax to pass info to php
$.ajax({
url: 'php/ProcessOrder.php',
data: {my_json_data: json},
type: 'POST',
async: false,
dataType: 'json', cache:false
});
});