Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

php - 将PHP数组传递给JavaScript函数[重复](Pass a PHP array to a JavaScript function [duplicate])

This question already has an answer here:(这个问题已经在这里有了答案:)

How do I pass variables and data from PHP to JavaScript?(如何将变量和数据从PHP传递到JavaScript?) 19 answers(19个答案)

I am trying to get a PHP array variable into a JavaScript variable.(我正在尝试将PHP数组变量转换为JavaScript变量。)

This is my code:(这是我的代码:) <html> <head> <script type="text/javascript"> function drawChart(row,day,week,month,date) { // Some code... } </script> </head> <body> <?php for($counter = 0; $counter<count($au); $counter++) { switch($au[$counter]->id) { case pageID.'/insights/page_active_users/day': $day[] = $au[$counter]->value; break; case pageID.'/insights/page_active_users/week': $week[] = $au[$counter]->value; break; case pageID.'/insights/page_active_users/month': $month[] = $au[$counter]->value; break; } } ?> <script> drawChart(600/50, '<?php echo $day; ?>', '<?php echo $week; ?>', '<?php echo $month; ?>', '<?php echo createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day')))); ?>'); </script> </body> </html> I can't get value of the PHP array.(我无法获得PHP数组的价值。) How do I fix this problem?(我该如何解决这个问题?)   ask by Chirayu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use JSON .(使用JSON 。)

In the following example $php_variable can be any PHP variable.(在以下示例中, $php_variable可以是任何PHP变量。) <script type="text/javascript"> var obj = <?php echo json_encode($php_variable); ?>; </script> In your code, you could use like the following:(在您的代码中,您可以使用以下代码:) drawChart(600/50, <?php echo json_encode($day); ?>, ...) In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:(在需要从JSON字符串解析对象的情况下(例如在AJAX请求中),安全的方法是使用JSON.parse(..) ,如下所示:) var s = "<JSON-String>"; var obj = JSON.parse(s);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...