1
我想通過JQuery將json文件傳遞給PHP。當我檢查響應時,我得到錯誤json_decode期望參數1是一個字符串。發佈json文件到PHP
這裏是我的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?
感謝您的任何幫助
轉儲變量,看看你會得到什麼。 'var_dump($ _ POST ['my_json_data']);' –
它包含html以及'標題' = >字符串 Mr'(長度= 2) '名字'<字體顏色= '#888a85'> = >串<字體顏色= '#CC0000'> '12'(長度= 2) 「姓' = >字符串'12'(長度= 2) '組名稱'<字體顏色= '#888a85'> = >串<字體顏色= '#CC0000'> '爲'(長度= 2) – user2247671