如何将PHP数组传递给JavaScript函数?

时间:2014-06-24 11:09:45

标签: javascript php joomla

首先,这个问题看起来与Pass a PHP array to a JavaScript function重复,但我实际上使用了Pass a PHP array to a JavaScript function的第一个解决方案 - 它似乎无法正常工作:

更具体地说,下面代码中的php echo行似乎根据控制台错误消息创建了错误的js输出(Uncaught SyntaxError:Unexpected token&lt;);控制台显示以"var s1 = <br /> <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1'..."

开头创建的html

...虽然我期待一个干净的var s1 = [1,2,3,4,5,6,7,8,9] - 我在ideone.com上测试回声线时也会看到结果

知道为什么回声线会创建这个东西,以及如何解决这个问题?

相关的joomla php代码:

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();

//add jqplot libraries
JHtml::_('jquery.framework');

JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.js');
//$document->addStyleSheet(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHtml::stylesheet( JUri::root() . 'media/system/js/jquery.jqplot.min.css' );
JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHTML::script(JUri::root() .'media/system/js/jqplot.barRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.categoryAxisRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.pointLabels.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.enhancedLegendRenderer.js');
JHTML::script(JUri::root() .'media/system/js/weqlib.js');

$chartvals = array(1,2,3,4,5,6,7,8,9);
?>

<head>
<script type="text/javascript">

    jQuery(document).ready(function(){
        var s1 = <?php echo json_encode(chartvals); ?>; //!the echo seems to create erroneous js output accoding to console(?)

        plot1 = jQuery.jqplot ('chart1', [s1]); //copied from example at 


    }); //$(document).ready
</script>
</head>

2 个答案:

答案 0 :(得分:3)

您忘记$chartvals函数调用中引用json_encode() var:

var s1 = <?php echo json_encode(chartvals); ?>;

应该是

var s1 = <?php echo json_encode($chartvals); ?>;

为了不再陷入此类错误,您可以将error_reporting(E_ALL);添加到脚本的开头,并在开发过程中将display_errors设置为PHP配置中的on

答案 1 :(得分:1)

var s1 = <?php echo json_encode($chartvals); ?>; //!the echo seems to create