我正在通过JSON将JSON数据从jQuery脚本发送到php文件,在该文件中,我试图将其拆分为变量,以便将其全部上传到数据库中。到目前为止,JSON数据已作为JSON对象发送和接收,但我无法提取任何数据。
jquery脚本
<html>
<head>
<script src="../jquery-3.1.0.min.js"></script>
<script>
function update(){
var x = {"1":{"item":"leaks", "qty":"2", "store":"fruitVeg"},"2":{"item":"chicken stock", "qty":"1", "store":"pan"}};
var dataSend = JSON.stringify(x);
$.ajax({
url:"updateTest.php",
type: "POST",
data: dataSend,
dataType: "json",
success: function(data){
var x = data.item;
console.log(data);
//$('#added').text(x +' Added');
}
});
}
$(document).ready(function(){
$('#add').click(update);
});
</script>
</head>
<body>
<div> <input type='button' value='Add to Shopping' id='add'/></div>
</body>
</html>
PHP脚本
<?php
$obj = json_decode(file_get_contents('php://input'), true);
$count = count($obj);
$test = $obj[1]['item'];
//echo json_encode ($obj);
echo $count;
echo $test;
?>
目前,我返回的只是行数。如果我注释掉echo并取消注释echo json,则会返回以下内容
{1: {item: "leaks", qty: "2", store: "fruitVeg"}2: {item: "chicken stock", qty: "1", store: "pan"}
答案 0 :(得分:0)
我设法使用以下脚本使其工作
<html>
<head>
<script src="../jquery-3.1.0.min.js"></script>
<script>
function update(){
var x = [{"item":"leaks", "qty":"2", "store":"fruitVeg"},{"item":"chicken stock", "qty":"1", "store":"pantry"}];
var dataSend = JSON.stringify(x);
$.ajax({
url:"updateTest.php",
type: "POST",
data: "data="+dataSend,
success: function(data){
var x = data.item;
console.log(data);
//$('#added').text(x +' Added');
}
});
}
$(document).ready(function(){
$('#add').click(update);
});
</script>
</head>
<body>
<div> <input type='button' value='Add to Shopping' id='add'/></div>
</body>
</html>
php看起来像这样
<?php
$list = stripslashes($_REQUEST["data"]);
$obj = json_decode($list);
echo $item1 = $obj[0]->item;
echo $item2 = $obj[1]->item;
?>