试图将查询结果发送到javascript数组或其他东西。
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<title>Admin check</title>
<meta charset="UTF-8">
</head>
<body>
<script type='text/javascript'>
<?php
include 'pdo_connect.php';
function pleaseWork() {
return dataQuery("SELECT * FROM `grupy`")->fetchAll();
}
$work = pleaseWork();
echo "jArray = JSON.parse(<?php echo JSON_encode($work);?>);";
?>
</script>
得到类似的代码,结果如下:
<br />
<b>Notice</b>: Array to string conversion in <b>/virtual/chemioterapia2137.cba.pl/adminCheck.php</b> on line <b>20</b><br />
jArray = JSON.parse(<?php echo JSON_encode(Array);?>); //jArray = JSON.parse('');
我怎样才能让它发挥作用?
答案 0 :(得分:3)
只需将其更改为:
echo "var jArray = JSON.parse(". JSON_encode($work) .");";
答案 1 :(得分:3)
有几个错误:
json_encode
时,它已经将您的数组转换为可读的JS对象。所以不需要解析。以这种方式重写代码,我手动创建了数组结果以模仿数据库结果:
<?php
function pleaseWork()
{
return array(
array(
"name" => "John",
"age" => 52
),
array(
"name" => "Jane",
"age" => 48
)
);
}
$work = pleaseWork();
$json = json_encode($work);
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<title>Admin check</title>
<meta charset="UTF-8">
</head>
<body>
<script type='text/javascript'>
var jArray = <?= $json ?>;
console.log(jArray);
</script>
</body>
</html>
浏览器的控制台结果:
0: Object
age: 52
name: "John"
1: Object
age: 48
name: "Jane"