javascript - 集成 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 数组的最佳方法是什么?
解决方案
您可以遍历结果以构建与您的 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
推荐阅读
- java - Springboot如何在服务器重启时轮换日志文件
- sql - 关于 groupby 原因的 Sql Query 问题和错误
- angular - 将任何输入中按下的键转换为大写
- c# - c# WPF App.Current 在自定义对话框窗口关闭后变为空
- javascript - 有没有同时涵盖 Null 和 Undefined 的词?
- ruby-on-rails - 如何解决 Google Cloud Rails 部署问题
- r - 尝试使用 dplyr 在 R 中查找行总和,然后过滤掉列
- javascript - node.js - 将使用 'space.repeat' 缓冲在浏览器中的工作方式相同
- powershell - 为什么我的 powershell 脚本中的文档对象是空值?
- javascript - 如何在本机反应中访问状态中的外部函数值