首页 > 解决方案 > 集成 php 和 Javascript 的最佳方式

问题描述

我有一个 .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 数组的最佳方法是什么?

标签: javascriptphpjquery

解决方案


您可以遍历结果以构建与您的 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


推荐阅读