在带有 Ajax 的 Javascript 文件中传递并使用 PHP 变量

Pass and use a PHP variable in a Javascript file with Ajax

我有一个 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')。 但是当我使用数据类型 'text' 而不是 'Json' 时,成功函数就可以了,我有 alert(data).
如何解释这种行为?我如何解析 PHP 变量 $instruction ?

非常感谢任何帮助,谢谢!

  1. 无需手动创建 json 字符串。只需构建和排列并将其编码为 json 和 json_encode()
  2. 已经response headers
  3. 中设置JSON内容类型
  4. 结束 ?> 标签是多余的,不建议使用(参见 PSR-12

所以最终你的代码应该是这样的

<?php

require_once 'connection.php';

$query1 = pg_query("This_is_my_query");

$instructions = [];
while ($row = pg_fetch_array($query1)) {
    $row1 = $row['row1'];
    $row2 = $row['row2'];
    $instructions[] = ['name' => $row1, 'y' => $row2];
}

header('Content-Type: application/json; charset=utf-8');

echo json_encode($instructions);