javascript - 从 php json 解码中检索 json 数组

标签 javascript php json ajax

我有一个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/

相关文章:

javascript - 使用 Webgl 时 Firefox "This operation requires zeroing texture data"警告

javascript - 使用 FB.ui 在应用程序请求中设置好友 ID?

javascript - 将元素粘贴到滚动固定元素的底部?

javascript - Passport.js 使用 MySQL 和 Node.js 成功登录挂起,没有错误

javascript - 在 PHP 中从 JSON_decode 数组访问值

PHP从文件中读取和写入JSON

json - 如何使用 jQuery 创建 JSON 对象

php - 同一范围内的两个 foreach 具有相同的变量名(第一个使用引用)

php - 插入多个用户和随 secret 码 Php Mysql

php - 如何使用左连接更新多个(5)表?