最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I convert PHP variables to JavaScript variables? - Stack Overflow

programmeradmin3浏览0评论

I am trying to insert php variables into javascript.

Here is the broken code:

 var tokens = [<?
 $result = mysql_query("SELECT * FROM accounts ORDER BY id DESC") or die (mysql_error()); 
 while ($row = mysql_fetch_array($result)) { 
 $user_name = $row['user'];
 $user_id = $row['id'];
 echo "['$user_name','$user_id'],";
 }
 ?>]

I am trying to insert php variables into javascript.

Here is the broken code:

 var tokens = [<?
 $result = mysql_query("SELECT * FROM accounts ORDER BY id DESC") or die (mysql_error()); 
 while ($row = mysql_fetch_array($result)) { 
 $user_name = $row['user'];
 $user_id = $row['id'];
 echo "['$user_name','$user_id'],";
 }
 ?>]
Share Improve this question edited Nov 2, 2009 at 0:37 Peter Boughton 112k32 gold badges123 silver badges177 bronze badges asked Nov 2, 2009 at 0:07 RickstarRickstar 6,20921 gold badges57 silver badges74 bronze badges 3
  • 1 And which is the question? Any error? – Nathan Campos Commented Nov 2, 2009 at 0:09
  • I've attempted a quick clarification of the question. Hopefully Gully will confirm that this is what he's trying to do. – Peter Boughton Commented Nov 2, 2009 at 0:39
  • Duplicate of stackoverflow./questions/1663750/… – Kevin Peno Commented Nov 2, 2009 at 23:36
Add a ment  | 

3 Answers 3

Reset to default 4

Use PHP's json_encode & then echo out to javascript directly, e.g:

$fruit = array("banana", "apple", "strawberry", "raspberry", "orange");
$json_fruit = json_encode($fruit);

echo "var fruit = $json_fruit;";

Edit: I have updated this answer to no longer use eval() since it is not required. I had just started using JSON when I first answered this question.

You do this:

 echo "['$user_name','$user_id'],";

... meaning that it will generate this:

[ ['a','b'], ['a','b'], ['a','b'], ['a','b'], ]

Notice that it will always end with a "," and this is an incorrect syntax.

Correct syntax is :

[ ['a','b'], ['a','b'], ['a','b'], ['a','b'] ]

I'm not a PHP guy, but I'd say something like this would fix it :

 var tokens = [<?
 $result = mysql_query("SELECT * FROM accounts ORDER BY id DESC") or die (mysql_error()); 
 $i = 0;
 while ($row = mysql_fetch_array($result)) { 
 $i++;
 $user_name = $row['user'];
 $user_id = $row['id'];
 echo "['$user_name','$user_id']";
 if($i < sizeof($result)-1 ) // incorrect syntax, but you get the point
   echo ","
 }
 ?>]

PHP runs on the server. JavaScript runs on the client.

You can generate JavaScript from PHP, but you cannot run PHP in JavaScript.

(It is worthwhile reading up on how the various ponents of the web work, specifically HTTP, to understand all this better.)

If you want to perform PHP actions in response to client actions in the browser without reloading the whole page, investigate 'ajax'.

发布评论

评论列表(0)

  1. 暂无评论