【问题标题】:Pass and use a PHP variable in a Javascript file with Ajax使用 Ajax 在 Javascript 文件中传递和使用 PHP 变量
【发布时间】: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


【解决方案1】:
  1. 无需手动创建 json 字符串。只需使用json_encode() 构建和排列并将其编码为 json
  2. 必须response headers 中设置 JSON 内容类型
  3. 关闭?&gt;标签是多余的,不推荐使用(见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);

【讨论】:

  • 很好用!非常感谢@Hast !!
猜你喜欢
  • 2023-01-24
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
相关资源
最近更新 更多