【发布时间】:2022-01-22 05:28:17
【问题描述】:
我有一个 PHP 脚本,我可以在其中将查询的内容放入 Postgresql 数据库:
<?php
require_once 'connection.php';
$query1 = pg_query("This_is_my_query");
$instruction = "[";
while ($row = pg_fetch_array($query1)) {
$row1= $row['row1'];
$row2= $row['row2'];
$instruction .= "{name : '". $row1. "', y : ". $row2. "},";
}
$instruction .= "]";
echo $instruction;
?>
echo $instruction 给出:
[{name : 'Prestation', y : 1}]
然后我有一个 JS 文件,我尝试在其中显示和使用 $instruction 变量。
我使用 Ajax,我的脚本就是这样一个:
$.ajax({
url : 'Path_To_Php_File_Is_OK', // requesting a PHP script
dataType : 'json',
type: "GET",
async : false,
success : function (data) { // data contains the PHP script output
alert(data);
},
error: function(data) {
alert('error');
},
})
结果是没有调用成功函数,我有alert('error')。
但是当我使用 dataType 'text' 而不是 'Json' 时,成功功能没问题,我有 alert(data)。
如何解释这种行为?我该如何解析 PHP 变量 $instruction ?
非常感谢任何帮助,谢谢!
【问题讨论】:
-
我相信您需要从 PHP 发送 JSON 标头。您还应该使用
json_encode而不是手动创建 JSON。 -
请不要创建自己的 json 字符串。有些事情不可避免地会出错。相反,构建一个数组或对象并使用json_encode
标签: javascript php ajax