如何将PHP变量内容通过JS传入getJSON请求的data参数?
解决PHP变量传递给getJSON请求的问题
你的代码存在两处关键问题,导致变量无法正确传递到getJSON请求中,以下是修正方案:
1. 修复PHP变量转JS的语法问题
JS字符串变量必须用引号包裹,直接输出PHP变量会触发语法错误。更安全的做法是用json_encode自动处理转义,避免特殊字符破坏JS语法:
var tool = <?php echo json_encode($_REQUEST['tool']); ?>;
如果需要兼容tool参数不存在的场景,先在PHP层做判断:
<?php $tool = isset($_REQUEST['tool']) ? $_REQUEST['tool'] : ''; ?> <script type="text/javascript"> var tool = <?php echo json_encode($tool); ?>; // 后续代码... </script>
2. 修正getJSON中的变量引用错误
JS中引用变量不需要加$前缀,你写的$tool是PHP变量语法,改为原生JS变量名tool即可:
$.getJSON("fertigung/graph/mes/autocomplete/getdata_error_vs_error_category.php?type=json", { tool: tool }, function(data) {
修正后的完整代码
<script type="text/javascript"> window.onload = function () { var tool = <?php echo json_encode(isset($_REQUEST['tool']) ? $_REQUEST['tool'] : ''); ?>; $.getJSON("fertigung/graph/mes/autocomplete/getdata_error_vs_error_category.php?type=json", { tool: tool }, function(data) { var dataPoints = []; var chart = new CanvasJS.Chart("chartContainer",{ animationEnabled: true, animationDuration: 2000, exportEnabled: true, zoomEnabled: true, title:{ fontSize: 15, text:"Number of Fails vs. Diagnostic Part" }, axisX: { interval:1, labelMaxWidth: 300, labelAngle: 45, labelFontSize: 12, labelFontFamily: "tahoma", }, axisY: { title: "Number of Failed Diagnostics", labelMaxWidth: 300, labelFontSize: 12, labelFontFamily: "tahoma", }, data: [{ type: "column", dataPoints : data, }] }); chart.render(); }); } </script>
内容的提问来源于stack exchange,提问作者Para Doxs
相关产品推荐
相关产品推荐

