如何将json对象从php页面传递给js变量

时间:2016-04-23 01:35:02

标签: javascript php json

首先,我很抱歉,如果已经在另一篇文章中解决了这个问题 - 我确定它已经解决了,但我无法弄明白。

其次,我有一个PHP页面,它输出一个JSON格式的数组,如下所示:

[{
   "chemical":"Corrosion_Inhibitor",
   "TargetDose":81,
   "AppliedDose":26,
   "ppbbl":"$0.97"
},
{
   "chemical":"Scale_Inhibitor",
   "TargetDose":56,
   "AppliedDose":63,
   "ppbbl":"$1.00"
},
{
   "chemical":"Biocide",
   "TargetDose":55,
   "AppliedDose":55,
   "ppbbl":"$0.30"
},
{
   "chemical":"Friction_Reducer",
   "TargetDose":23,
   "AppliedDose":44,
   "ppbbl":"$0.42"
}] 

我想将该数组传递给JavaScript中的变量tableData,以便我可以在另一个PHP页面上填充表。任何指导将不胜感激。很明显,我不是这两种语言的专家。

2 个答案:

答案 0 :(得分:0)

听起来您想要从JSON响应中动态生成表吗?如果要向输出该JSON响应的php脚本发送请求,则可以使用JSON.parse(responseData)将JSON字符串响应解析为JS变量数组/对象数组。

答案 1 :(得分:0)

这是执行此操作的基本方法:

<?php 

$dataFromPHP =
'[{
   "chemical":"Corrosion_Inhibitor",
   "TargetDose":81,
   "AppliedDose":26,
   "ppbbl":"$0.97"
},
{
   "chemical":"Scale_Inhibitor",
   "TargetDose":56,
   "AppliedDose":63,
   "ppbbl":"$1.00"
},
{
   "chemical":"Biocide",
   "TargetDose":55,
   "AppliedDose":55,
   "ppbbl":"$0.30"
},
{
   "chemical":"Friction_Reducer",
   "TargetDose":23,
   "AppliedDose":44,
   "ppbbl":"$0.42"
}] 
';
?>
<html>
   <body>
       <!-- main HTML content -->
   </body>

   <script>
     var tableData = <?php echo $dataFromPHP ?>;

      // do whatever you want with that data
   </script>
</html>