json_encode无法正常工作,它不会打印json值

时间:2017-02-16 07:11:51

标签: php jquery json

<?php
    include("db_connection.php");
      if(isset($_POST['id']) && isset($_POST['id']) != "")
 {
// get User ID
$user_id = $_POST['id'];

// Get User Details
$query = "SELECT * FROM products WHERE id = '$user_id'";
if (!$result = mysql_query($query)) {
    exit(mysql_error());
}
$response = array();
if(mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $response[] = $row;         
    }
}
else
{
    $response['status'] = 200;
    $response['message'] = "Data not found!";
}   
// display JSON data
header('Content-type: application/json');
   echo json_encode($response); ;   

}
else
{
$response['status'] = 200;
$response['message'] = "Invalid Request!";
}
?>

上面的代码从主页获取一个值。从数据库中获取行并使用json将行传递给主页.echo json_encode($ response)不打印json值。是否将数组分配给$ response ?我需要做出哪些改变?帮帮我!!

2 个答案:

答案 0 :(得分:1)

json_encode要求您输入的所有数据都经过UTF-8编码,否则会失败。有关如何从数据库中获取UTF-8编码数据的信息,请参阅UTF-8 all the way through。(使用mysqli_set_charset)。

答案 1 :(得分:1)

Jquery的:

$.ajax({
    url: '[YOUR_AJAX_CONTROLLER_URL]',
    data: {
        format: 'json'
    },
    success: function (data) {
        if (data.status == 'success') {
            // your action when response status is success.
            // the user details are in data.items
        } elseif (data.status == 'error') {
            // your action when response status is error.
            // the error message is in data.message
        }
    },
    error: function () {
        // your action when request is not accepted.
        // there are no data from your PHP,
        // because this is server error, not PHP error.
    }
});

PHP:

<?php
    include("db_connection.php");

    if (isset($_POST['id']) && $_POST['id'] != "") {
        // get User ID
        $user_id = $_POST['id'];

        // Get User Details
        $query = "SELECT * FROM products WHERE id = '$user_id'";

        $response = array();

        if (!$result = mysql_query($query)) {
            $response = [
                'status' => 'error',
                'message' => mysql_error(),
            ];
        } else if (mysql_num_rows($result) > 0) {
            while ($row = mysql_fetch_assoc($result)) {
                $response = array(
                    'status' => 'success',
                    'item' => $row,
                );
            }
        } else {
            $response = [
                'status' => 'error',
                'message' => 'Data not found!',
            ]
        }   
    } else {
        $response = [
            'status' => 'error',
            'message' => 'Invalid Request!',
        ];
    }

    // display JSON data
    header('Content-type: application/json');
    echo json_encode($response);

&GT;