php 用php返回json数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37913147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:25:51  来源:igfitidea点击:

Return json data with php

phpjson

提问by Mike Henley

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?

我想返回 json 数据,但我的代码不起作用。我没有收到任何错误消息。我有 index.php、ajax.php 和 db.php。Db.php 正在运行。但是我的 ajax 代码不起作用。我的错误在哪里?

index.php:

索引.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:

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

回答by Darren

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

如果你期待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);

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

现在,您将看到,我们通过设置正确的Content-Type标头而不是将纯文本和 json 混合在一起来发送实际的 JSON 。

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

要在您的 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);
            }
        }
    });
});