我想返回json数据,但我的代码不起作用.我没有收到任何错误消息.我有index.php,ajax.php和db.php.Db.php正在工作.但我的ajax代码无效.我的错误在哪里?
index.php文件:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
</head>
<body>
<div id="test" style="width:500px;height:400px; margin:20px auto;"></div>
<script>
$(window).load(function () {
$.ajax({
dataType: "json",
url: 'ajax.php',
success:function(data){
$("#test").html(data);
}
});
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Ajax.php:
<?php
require 'db.php';
$query="select lat,lng from locations order by id";
$result = pg_query($link, $query);
if (!$result) {
echo "An error occurred_xxx.\n";
}else {
$arr = pg_fetch_all($result);
echo json_encode($arr);
} ?>
Run Code Online (Sandbox Code Playgroud)
如果你期望JSON你需要发送它,无论如何.当你的脚本错误发送时你正在做什么text/html.试试这个:
header("Content-Type: application/json");
require 'db.php';
$query="select lat,lng from locations order by id";
$result = pg_query($link, $query);
$response = array();
if (!$result) {
$response = array(
'status' => false,
'message' => 'An error occured...'
);
}else {
$response = array(
'status' => true,
'message' => 'Success',
'data' => ph_fetch_all($result)
);
}
echo json_encode($response);
Run Code Online (Sandbox Code Playgroud)
现在你会看到,我们发送实际的JSON,通过设置一个正确的Content-Type标题,而不是混合纯文本和json.
要在jQuery中处理此响应,只需调整响应:
$(window).load(function () {
$.ajax({
dataType: "json",
url: 'ajax.php',
success:function(data){
if(!data.status) {
$("#test").html("ERROR: " + data.message);
} else if(data.status) {
$("#test").html(data);
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18199 次 |
| 最近记录: |