简体   繁体   English

通过 Ajax 在 Javascript 文件中传递并使用 PHP 变量

[英]Pass and use a PHP variable in a Javascript file with Ajax

I have a PHP script in which I get the content of a query made into a Postgresql database:我有一个 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;
?>

The echo $instruction gives: echo $instruction给出:

[{name : 'Prestation', y : 1}]

Then I have a JS file in which I try to display and use the $instruction variable.然后我有一个 JS 文件,我尝试在其中显示和使用$instruction变量。
I use Ajax and my script is the one:我使用 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');
},
})

The result is that the success function is not called and I have the alert('error') .结果是没有调用成功 function 并且我有alert('error') But when I use the dataType 'text' and not 'Json', the success function is ok and I have the alert(data) .但是当我使用 dataType 'text' 而不是 'Json' 时,成功 function 是可以的,我有alert(data)
How to explain that behaviour?如何解释这种行为? And how could I parse the PHP variable $instruction ?我如何解析 PHP 变量$instruction

Any help would ve very appreciated, thanks !任何帮助将非常感激,谢谢!

  1. There is no need to create a json string manually.无需手动创建 json 字符串。 Just build up and array and encode it to json with json_encode()只需使用json_encode()构建和排列并将其编码为 json
  2. You have to set JSON content-type in the response headers必须响应标头中设置 JSON 内容类型
  3. Closing ?> tag is redundant and is not recommended to use (see PSR-12 )关闭?>标记是多余的,不建议使用(参见PSR-12

So eventually your code should look like this所以最终你的代码应该是这样的

<?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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM