简体   繁体   中英

Echo PHP variable in Javascript in PHP

This may seem like an odd question, and it may have been answered elsewhere...but frankly I'm not quite sure how to phrase a search any better.

Essentially, I am trying to write an entire HTML and Javascript page in PHP (this way I can easily call and manipulate SQL queries...I know it doesn't make a lot of sense, but it's my last resort for an upcoming deadline).

Anyways, I want to call/append to a PHP variable (the SQL query) in my Javascript...Something like this:

mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$myquery = "SELECT  `xxx`, `yyy` FROM `$tbl_name`";
$query = mysql_query($myquery);
$data = array();

for ($i = 0; $i < mysql_num_rows($query); $i++) {
    $data[] = mysql_fetch_assoc($query);
}

$data1 = json_encode($data);

echo '<!DOCTYPE html>
      <html>
          <head></head>
          <body>
              <script>
                  data_arr = {$data1}
                  ...
                  ...

This doesn't seem to be working though. I've tried:

    data_arr = {$data1}

and

    data_arr = {'.$data1.'}

No luck so far. Is there anything I can do?

Change the quotes to double quotes then use the data_arr = {$data1} one. Single quotes dont recognize values at all.

Try this, this might work:

PHP:

<?php $data1 = "hello"; ?>

JS:

var data_arr = {"<?=$data1?>"}

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