首先,我是JS和PHP的新手。但是我有一个PHP阵列,其中包含某些事件的标题。我正在尝试制作一个JavaScript脚本,以创建元素并用PHP数组中的字符串填充它们。
这是我想知道的。有没有办法做这样的事情:
function createCard(x) {
var event_title = "<?php echo $event_title[x]; ?>";
}
,或者如果有更好的方法可以做到这一点,我就愿意提出建议。谢谢!
编辑:
我只需将php数组转换为js a阵列就可以解决自己的问题
var event_title_arr = [<?php echo '"'.implode('","', $event_title ).'"' ?>];
您必须将php数组转换为字符串或JSON,并在JS中使用。
ex,数组到字符串,
function createCard(x) {
var event_title = "<?php echo implode(',', $event_title[x]); ?>";
var event_title_arr = event_title.split(',');
console.log(event_title _arr);
// play around using JS variable "event_title_arr "
}
或
function createCard(x) {
var event_title = "<?php echo json_encode($event_title[x]); ?>";
var event_title_arr = JSON.parse(event_title);
console.log(event_title _arr);
// play around using JS variable "event_title_arr "
}