weixin_33725722 2015-08-28 10:46 采纳率: 0%
浏览 21

将json文件发布到PHP

I am trying to pass a json file to PHP using Jquery. when I check the response I get the error json_decode expects parameter 1 to be a string.

Here is my jquery routine

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

here is my php script

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

?>

here is my json object

{"Title":"Mr","First Name":"12","Surname":"12","Group Name":"as"}

Using php fiddle I created and tested this script which worked perfectly

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

?>

One thing I did notice is my php fidle json file has [] the posted object doesn't is this what the error message refers too? Or Should I not JSON.stringfy() and just pass it as a string into php and use JSON_encode?

thanks for any assistance

  • 写回答

1条回答 默认 最新

  • YaoRaoLov 2015-08-28 10:52
    关注

    The JSON.stringify returns the encoded string. You have to post its returned value, not the parameter passed to it.

    // 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 
    }); 
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀