简体   繁体   English

如何在DOM中的php和javascript之间共享数据?

[英]How to share data between php and javascript in DOM?

If you read my previous question , you may know that the way of sharing data between php and javascript DOM is not permitted in this assignment: 如果您阅读我之前的问题 ,您可能知道在此作业中不允许在php和javascript DOM之间共享数据的方式:

+-----------+   +------------+  +----------| +----------+  +-----------+    
|javascript +---+Ajax Request+--+handle.php+-+result.xml+->+DOM parser |    
+-----------+   +------------+  +----------+ +----------+  +-----------+    

so I'm thinking about get all the information in the mysql all at once as an array, and try to access this array by javascript without ajax request. 所以我正在考虑将mysql中的所有信息一次性作为数组获取,并尝试通过javascript访问此数组而不使用ajax请求。

The only way that I can come up with is 我能想到的唯一方法是

   +---------+     +-----------------------------+  +--------------------------------------+
   |Php array|     | write in Dom make it hidden |  | Parse the hidden element by DOM API  |
   +---------+     +-----------------------------+  +--------------------------------------+ 

But this doesn't seems elegant at all, Is there a better way to do this? 但这看起来并不优雅,有没有更好的方法呢?

Query the database, and print the results as JavaScript inside a script tag. 查询数据库,并将结果作为JavaScript打印在脚本标记内。 Now all the data is sitting in local JavaScript variables that you can use however you want. 现在,所有数据都位于您可以使用的本地JavaScript变量中。

<script type="text/javascript">

  products = [];

  <?php
  mysql_connect('host', 'username', 'password');
  mysql_select_db('dbname');    

  $sql = "SELECT productName from products WHERE productTYPE = 1";
  $result = mysql_query($sql);
  while ($row = mysql_fetch_array($result)) {

    echo "products.push('" . addslashes($row['productName']) . "'); \n";

  }

  ?>

  //do something with all the stuff in the products array
  alert("There are " + products.length + " products in the array.");

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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