首页 文章

集成php和Javascript的最佳方式

提问于
浏览
-1

我有一个.php文件,我运行一些脚本来显示“卡片” . 我有6张牌显示,显示的文字是硬编码的 . 我准备开始从我的数据库中删除并删除我的硬代码部分 .

//Set number of cards to show
    multiplyNode(document.querySelector('.card_content'), 6, true);  

    var authors = ["Margaret", "Lucy", "Odessa", "Shifty", "Saggy", "Lady"];
    var BookNumbers = [2563, 8547, 5896, 4157, 5823, 7963];
        $(function(){box_title

        //$(".card_content").clone(true).appendTo(".main_card_shell");
        $('.box_title').each(function (i) { 
            $(this).html("<div class='card_name'>" + authors[i] + "</div>" +
            "<div class='card_number'>" + BookNumbers[i] +  "</div>" +
                            "<div class='tag_row'>" +
                                "<div class='sample_tag sample_tag4'></div>" +
                                "<div class='sample_tag sample_tag3'></div>" +
                            "</div>");

        });

    })

我知道我可以通过以下方式从数据库中提取我想要的数据:

$result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");

但是如何让我的$ result替换我的硬编码作者和BookNumbers数组的最佳方法是什么?

1 回答

  • 0

    您可以遍历结果以构建与javascript数组具有相同结构的php数组,然后使用 json_encode 将其转换为javascript数组格式 .

    <script type='text/javascript'>
    <?php
    $result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");
    // loop through the results to build the php arrays
    while($row = $result->fetch_array())
    {
        // set the author and book number to array with numeric key
        $authors[] = $row['Author'];
        $BookNumbers[] = $row['Book_Num'];
    }
    // use json_encode to convert the php array to an javascript array
    echo "var authors = ".json_encode($authors).";\n";
    echo "var BookNumbers = ".json_encode($BookNumbers).";\n";
    ?>
    </script>
    

    评论:除非你需要交互性,你可以使用php构建html而不使用jquery

相关问题