I've used php's json_encode()
function many times, but for some reason I can't seem to find the problem here...
我已多次使用php的json_encode()函数,但出于某种原因我似乎无法在这里找到问题...
Note: I've removed error checking for clarity purposes.
注意:为了清晰起见,我删除了错误检查。
//PHP
// PHP
<?php
session_start();
require 'global/query.php';
$sql = "SELECT sfl,station,latitude,longitude,address,city FROM maps";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$trows[] = $result;
}
echo json_encode($trows);
?>
I'm using AJAX and am just console.log()
-ing the output to print the response like so...
我正在使用AJAX而且只是console.log() - 输出打印响应就像这样......
//JS
// JS
var callback = {
"projects": function(e){
console.log(e.target.response);
}
};
In the console it prints a blank line with none of the data...
在控制台中,它打印一个空白行,没有数据......
Now if I var_dump
the $trows
the output in the console will print the data so I know my sql statement works just fine...
现在,如果我var_dump $ trows,控制台中的输出将打印数据,所以我知道我的sql语句工作正常...
//PHP
// PHP
var_dump($trows);
//CONSOLE
//安慰
array(522) {
[0]=>
array(6) {
["sfl"]=>
string(1) "1"
["station"]=>
string(26) "COMPRESSOR STATION"
["latitude"]=>
string(2) "23"
["longitude"]=>
string(4) "-115"
["address"]=>
string(10) "Unnamed Rd"
["city"]=>
string(9) "blah"
}
[1]=>
array(6) {
["sfl"]=>
string(1) "2"
["station"]=>
string(17) "STA TERMINAL"
["latitude"]=>
string(2) "16"
["longitude"]=>
string(4) "-101"
["address"]=>
string(11) "15 Ranch Dr"
["city"]=>
string(8) "Blah Blah"
},
Questions: Why isn't my php's json_encode function working? I've used this exact code before and the output was fine.
问题:为什么我的php的json_encode功能不起作用?我之前使用过这个确切的代码,输出很好。
2 个解决方案
#1
3
Try and add:
尝试并添加:
header("Content-type: application/json; charset=utf-8");
Before you echo your JSON encoded result.
在回显JSON编码结果之前。
EDIT:
编辑:
If the encoding doesn't work try the following:
如果编码不起作用,请尝试以下操作:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
$trows[] = array_map('utf8_encode', $result);
}
#2
1
I would see what PHP tells you:
我会看到PHP告诉你的内容:
Change
更改
echo json_encode($trows);
to
至
$json = json_encode($trows);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
echo json_last_error_msg();
} else {
echo $json;
}
#1
3
Try and add:
尝试并添加:
header("Content-type: application/json; charset=utf-8");
Before you echo your JSON encoded result.
在回显JSON编码结果之前。
EDIT:
编辑:
If the encoding doesn't work try the following:
如果编码不起作用,请尝试以下操作:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
$trows[] = array_map('utf8_encode', $result);
}
#2
1
I would see what PHP tells you:
我会看到PHP告诉你的内容:
Change
更改
echo json_encode($trows);
to
至
$json = json_encode($trows);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
echo json_last_error_msg();
} else {
echo $json;
}