用php返回json数据 [英] Return json data with php

查看:102
本文介绍了用php返回json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回json数据,但是我的代码无法正常工作.我没有收到任何错误消息.我有index.php,ajax.php和db.php. Db.php正在工作.但是我的ajax代码无法正常工作.我的错误在哪里?

I want to return json data but my code is not working. I don't get any error message. I have index.php, ajax.php and db.php. Db.php is working. But my ajax code is not working. Where is my mistake?

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>      

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

推荐答案

如果您期望JSON,则无论如何都要发送它.脚本错误时您正在做什么,正在发送text/html.试试这个:

If you're expecting JSON you need to send it regardless. What you're doing when your script errors, is sending text/html. Try this:

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

现在,如您所见,我们通过设置正确的Content-Type标头而不是混合纯文本和json来发送实际的JSON.

Now as you'll see, we send actual JSON, by setting a correct Content-Type header and not mixing plain text and json up.

要在jQuery中处理此响应,只需对响应进行条件处理:

To handle this response within your jQuery, simply condition the response:

$(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);
            }
        }
    });
});

这篇关于用php返回json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆