我有一个javascript来创建json数组,它有一个ajax post方法,我必须知道这个json数组应该如何在php端解码?
我的 JavaScript 函数:
var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"datee" : "2017-09-09" ,"total" : tot }], invoiceLine: []};
for(i=1; i<=count+arr.length-1; i++){
var ss = String(i);
if(arr.includes(ss)){
continue;
}
invoices.invoiceLine.push({
"itemName" : document.getElementById('item'+i).value ,
"qty" : document.getElementById('inputQty'+i).value ,
"value" : document.getElementById('value'+i).value
});
}
$.ajax({
type: "POST",
url: "saveInvoice.php",
data: {json : JSON.stringify(invoices)},
cache: false,
success: function(data) {
alert(data);
location.reload();
}
});
这是我的php:(它不会将数据保存到数据库中。我现在希望将第一个发票数据保存在数据库中。然后我可以使用invoiveLine数据插入另一个表。)
$dbhost = "localhost";
$dbuser = "root";
//$dbpass = "dbpassword";
$dbname = "inventory";
$jsonInvoice = json_decode($POST['invoices'],true);
$customerName = $jsonInvoice.["invoice"][0].["customerName"];
$reciptionName = $jsonInvoice.["invoice"][0].["reciptionName"];
$date = $jsonInvoice.["invoice"][0].["datee"];
$total = $jsonInvoice.["invoice"][0].["total"];
mysql_connect($dbhost, $dbuser, '');
mysql_select_db($dbname) or die(mysql_error());
$query = "insert into invoice (customerName,reciptionName,date,total) values ('$customerName','$reciptionName','$date',$total)";
$qry_result = mysql_query($query) or die(mysql_error());
$insertId = mysql_insert_id();
echo $insertId;
最佳答案
你能试试这个吗:
$customerName = $jsonInvoice["发票"][0]["customerName"];
我认为您遇到了由点引起的语法错误。 json_decode 返回一个数组,您必须按照我上面编写的方式访问属性。 (有关更多信息,请参阅 this)
另外,请注意其他用户向您提供的有关 mysqli 的建议
关于javascript - 从 php json 解码中检索 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45135399/