我在使用json_decode解决问题时遇到了麻烦。我得到了一个有效的json,它是通过$ _POST发送的。
这是传递的JSON对象,库存变量:
[{"item_name":"Screw Driver","item_desc":"asdasd","item_type":"weapon"},
{"item_name":"Brown Shoes","item_desc":"asdasd","item_type":"footwear"}]
这是html javascript代码。
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "post" accept-charset="UTF-8">
<input type = "hidden" name = "inv" id = "inv"/>
<input type = "submit" id = "btn_save" onclick = "saveInventory()" value = "Save"/>
</form>
<script type = "text/javascript">
function saveInventory(){
var inv = document.getElementById("inv");
inv.value = inventory;
}
</script>
这是将从输入类型隐藏
获取json的php脚本<?php
if(isset($_POST['inv'])){
$inv = $_POST['inv'];
var_dump(json_decode($inv,true)); // returns NULL
}
?>
我一直在网上阅读很多json_decode问题但是大多数问题都有关于json_decode返回null的不同问题。有人可能会发现这里有什么问题吗?感谢。
答案 0 :(得分:1)
您的inventory
变量似乎是JavaScript对象数组,而不是JSON字符串。因此,您需要将其转换为JSON以将其存储在HTML输入值中:
function saveInventory(){
var inv = document.getElementById("inv");
inv.value = JSON.stringify(inventory); // convert to JSON string
}
答案 1 :(得分:0)
<?php
if(isset($_POST['inv'])){
$json=json_decode($_POST['inv']);
foreach($json as $j){
echo "NAME: ".$j->{"item_name"};
echo "<hr/>";
}
}
?>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'];?>">
<input type="text" name='inv' value='[{"item_name":"Screw Driver","item_desc":"asdasd","item_type":"weapon"},{"item_name":"Brown Shoes","item_desc":"asdasd","item_type":"footwear"}]'/>
<input type="submit" value="SEND"/>
</form>