简体   繁体   English

如何从php jsonObject中获取值(使用Javascript)(数据库条目)

[英]How to get the values(with Javascript) out of an php jsonObject(database entries)

I am trying to get values out of a database table and put them into a pdf document with javascript. 我正在尝试从数据库表中获取值,并将其放入带有javascript的pdf文档中。 I got the jsonobject from my php script but if I am trying to get the values it says "undefine". 我从php脚本中获取了jsonobject,但是如果我尝试获取值,它会显示“未定义”。

            $dbh = new PDO('mysql:host=localhost;dbname=onlinebestellung', 'root', '');
            $dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);

            $stmt = $dbh->prepare('SELECT * FROM artikelbestellung ');
            $stmt->execute();

            $result = $stmt->fetchAll();
            $json=json_encode($result);
            echo $json;
             $.ajax({
                 type: 'POST',
                 url: 'includes/rechnung.php',
                     success: function(result) {
                    var jsonData = JSON.parse(result);
                    alert(jsonData);
                     /* alert(jsonData); */
                     var pdf2 = new jsPDF("p", "mm", "a4");
                     pdf.text ("Test:" + jsonData.artikelnummer , 20, 80);
                     pdf.save ("rechnung123.pdf");

    }
}); 

alert shows: "object Object". 警报显示:“对象对象”。 my database table has 4 fields(id, rechnungsnummer, artikelnummer, anzahl) 我的数据库表有4个字段(id,rechnungsnummer,artikelnummer,anzahl)

You need to change your javascript code to follow: 您需要更改您的JavaScript代码以遵循:

$.ajax({
    type: 'POST',
    url: 'includes/rechnung.php',
    success: function(result) {
        var jsonData = JSON.parse(result);
        var pdf2 = new jsPDF("p", "mm", "a4");
        pdf.text ("Test:" + jsonData[0].artikelnummer , 20, 80);
        pdf.save ("rechnung123.pdf");
    }
}); 

As you can see when you fetch the data from database it will add it to array with index and to access the value you need to call the row number as index and then the column name itself. 如您所见,当您从数据库中获取数据时,它将把它添加到带有索引的数组中,并且要访问该值,您需要将行号称为索引,然后将列名本身调用。

I hope this helps. 我希望这有帮助。

Let me know if you need more help to this. 让我知道您是否需要更多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM