上下文
我正在构建一个WordPress主题模板,并试图使用WordPress和核心WordPress函数将一个数据数组从高级自定义字段> Repeater字段传递到JavaScript / HTML5饼图。
问题
我不知道如何以JS理解的格式将PHP数据传递给JS。
问题
我不确定我是否正确地提出了问题,或者正确地思考了问题。例如,我相信我可以使用JS直接与数据库通信。但我认为问题是:
码
这是我的代码:
<?php
if( have_rows('tpc_psmr_referrer') ):
while ( have_rows('tpc_psmr_referrer') ) : the_row();
$tpc_psmr_referrer_type = get_sub_field('tpc_psmr_referrer_type');
$tpc_psmr_referrer_platform = get_sub_field('tpc_psmr_referrer_type_platform'); // This needs to get passed as an array to the JS below.
endwhile;
endif;
?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2], // This is where the PHP array needs to be output.
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'Revenue'
};
var chart1 = new google.visualization.PieChart(document.getElementById('piechart1'));
chart1.draw(data1, options);
var data2 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'Budget'
};
var chart2 = new google.visualization.PieChart(document.getElementById('piechart2'));
chart2.draw(data2, options);
}
</script>
发布于 2018-05-07 14:05:22
查看PHP中的json_encode()‘值,并回显包含这些值的数据结构。$.ajax()请求脚本,并解析/适当在成功回调的前端返回的JSON。
更具体地说,要获得有关流程中所涉及的机制的更多信息的链接,请查看json_encode at php.net (示例1很简单):
http://php.net/manual/en/function.json-encode.php
以及关于jQuery的$.ajax API文档:
http://api.jquery.com/jquery.ajax/
SCRIPT.PHP
<?php
header("Content-type: application/json");
$data_array = ['one','two','three'];
$json = json_encode($data_array);
echo $json;
?>
JS
$('document').ready(function() {
$.ajax({
type:'POST',
url:'/the/path/to/script.php',
dataType:'JSON',
data:{
},
success:function(data){
$.each(data,function(x,y) {
console.log(data[x]);
});
},
error:function(jqXHR,textStatus,errorThrown){
console.log('Could not retrieve JSON');
}
});
});
发布于 2018-05-07 14:11:06
<?php $data_array = [1,2,3...]; ?>
<html>
<div id='yellowstone' hidden>
<?php echo json_encode($data_array); ?>
</div>
</html>
<script>
var array = JSON.parse(document.getElementById('yellowstone').innerHTML);
</script>
发布于 2018-05-07 14:13:49
WordPress有一个名为wp_localize_script
的函数。它允许您将数组传递给脚本,然后作为对象访问JS中的数组。
例如:
wp_localize_script( 'your_script', 'your_script_data',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'var_1' => 'value 1',
'var_2' => 'value 2',
)
);
然后在你的JS的某处
alert(your_script_data.var_1)
将显示value 1
ajax_url
包含和URL用于进行AJAX调用,以防您也需要这样做。这里是对此的一些解释。
https://stackoverflow.com/questions/50222942
复制相似问题