简体   繁体   中英

PHP echo javascript with PHP variable

I am currently displaying javascript via PHP echo:

        echo 'var currentInvoiceDataJSON = <?php echo json_encode($yearData_Invoices[$currentYear] ); ?>;';

However I get a Uncaught SyntaxError: Unexpected token < error which I infer is related to the second

How can I get this resolved and there any other possibilities?

Some expert advise would be appreciated.

That code ends as invalid Javascript code.

Here's what happens:

Your server echoes a string:

echo 'var currentInvoiceDataJSON = <?php echo json_encode($yearData_Invoices[$currentYear] ); ?>;';

Your browser now has:

var currentInvoiceDataJSON = <?php echo json_encode($yearData_Invoices[$currentYear] ); ?>;

Once your PHP script finishes running and echoes that first string, PHP cannot process the inner echo.


What I would do:

$data = json_encode($yearData_Invoices[$currentYear]);
echo 'var currentInvoiceDataJSON = ' . $data . ';';

改为这样做:

echo 'var currentInvoiceDataJSON = '.<?php echo json_encode($yearData_Invoices[$currentYear] ); ?>.';';

我没有测试过,但可以尝试一下:

echo "var currentInvoiceDataJSON = '".str_replace("'","\\'",json_encode($yearData_Invoices[$currentYear]))."';";

just change to

echo "var currentInvoiceDataJSON = ".json_encode($yearData_Invoices[$currentYear] ).";";

and also be aware that single quoted strings in php don't interpolate variables so

$a = "Hello World";
echo '$a'; // outputs :  $a
echo "$a"; // outputs :  Hello World

and when you are in a php context

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