简体   繁体   中英

How to Pass a PHP array to JavaScript function?

First of all, this question looks a duplicate of Pass a PHP array to a JavaScript function , but I actually used the first solution of Pass a PHP array to a JavaScript function - and it doesnt seem to work:

More specifically, the php echo line in the code below seems to create erroneous js output according to console error message( Uncaught SyntaxError: Unexpected token <); the console shows created html starting with "var s1 = <br /> <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1'..."

...while I'd expect a clean var s1 = [1,2,3,4,5,6,7,8,9] - the result I also see when I tested the echo line in ideone.com

Any idea why the echo line is creating this stuff, and how to fix this?

Related joomla php code:

<?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>

You forgot the $ to referrence the chartvals var at the json_encode() function call:

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

Should be

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

To not trap into this sort of mistakes again you can add error_reporting(E_ALL); to the beginning of your script and set display_errors to on in your PHP config during development.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM