为什么json_encode返回数组而不是对象?

时间:2016-05-28 16:12:10

标签: javascript php jquery json

如果您倾向于对此问题进行投票,请说明理由,以便我可以从错误中吸取教训。

PHP - 编辑

<?php

require_once "dbconnect.php";

function isEmpty($str) {
    return strlen(trim($str)) == 0;
}

function getWritersData() {
    try {
        if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
            throw new Exception('A user-id must be supplied.');       
        }
        $userid = $_REQUEST["userid"];
        $dbh = connect2DB();
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $dbh->prepare("SELECT Title, WorkType, FormType, Genre, NumberOfPages, Filename, OriginalFilename FROM Writers WHERE fkAccounts = :userid");
        $stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll();
        echo json_encode($rows, JSON_FORCE_OBJECT);
    } catch (PDOException $e) {
        echo 'Database error: ' . $e->getMessage();
    } catch (Exception $e) {
        echo 'General error: ' . $e->getMessage();
    }
}    
/** Update writers data **/
function saveWritersData() 
{
    try {
        include_once "commonWritersPostElements";
        $dbh = connect2DB();
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $dbh->prepare("UPDATE Writers SET fkAccounts=:userid, Title=:title, WorkType=:worktype, FormType=:formtype, Genre=:genre, NumberOfPages=:pages, Filename=:filename, OriginalFilename=:origonal WHERE fkAccounts=:userid");
        $worktype = "1";            
        $stmt->bindParam(':userid', $userid, PDO::PARAM_INT, 10);
        $stmt->bindParam(':title', $title, PDO::PARAM_STR, 255);
        $stmt->bindParam(':worktype', $worktype, PDO::PARAM_STR, 30);
        $stmt->bindParam(':formtype', $formtype, PDO::PARAM_STR, 30);
        $stmt->bindParam(':genre', $genre, PDO::PARAM_STR, 100);
        $stmt->bindParam(':pages', $nbrPages, PDO::PARAM_STR, 100);
        $stmt->bindParam(':filename', $NewFileName, PDO::PARAM_STR, 30);
        $stmt->bindParam(':original', $File_Name, PDO::PARAM_STR, 30);        
        $stmt->execute();

    } catch (PDOException $e) {
        echo 'Database error: ' . $e->getMessage();
    } catch (Exception $e) {
        echo 'General error: ' . $e->getMessage();
    }
}    
function deleteWritersData() 
{
    try {
        if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"]))
            throw new Exception('user-id is missing.');       
        else {
            $userid = filter_var(trim($_REQUEST["user-id"]), FILTER_SANITIZE_STRING);
            $userid = htmlspecialchars_decode($userid, ENT_QUOTES);
        }
        $dbh = connect2DB();
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $dbh->prepare("DELETE Writers WHERE fkAccounts=:userid");
        $stmt->bindParam(':userid', $userid, PDO::PARAM_INT, 10);
        $stmt->execute();

    } catch (PDOException $e) {
        echo 'Database error: ' . $e->getMessage();
    } catch (Exception $e) {
        echo 'General error: ' . $e->getMessage();
    }
}    


if (!isset($_REQUEST['action'])  || isEmpty($_REQUEST['action']))
    throw new Exception('Programmer error: action not posted.');
else {
    $action = $_REQUEST['action'];
    switch($action) {
    case 'get-writer-data':
        getWritersData();
        break;
    case 'update-writers':
        select();
        break;
    default:
        throw new Exception("Unknown action: " . $action);
        break;
    }
}

if (!isset($_REQUEST['action'])  || isEmpty($_REQUEST['action']))
    throw new Exception('Programmer error: action not posted.');
else {
    $action = $_REQUEST['action'];
    switch($action) {
    case 'get-writer-data':
        getWritersData();
        break;
    case 'delete-writers':
        deleteWritersData();
        break;
    case 'update-writers':
        saveWritersData();
        break;
    default:
        throw new Exception("Unknown action: " . $action);
        break;
    }
}

?>

JS

$(function () {
    populateWritersDropdowns();

    data = {};
    data.action = 'get-writer-data';
    data.userid = sessionStorage.getItem("user-id");
    console.log("user-id-manage-uploads=" + sessionStorage.getItem("user-id"))
    ajax('post', 'php/manage-uploads.php', data, getSuccess, "Error retrieving writer's data: ");
    $(".tr-clone");
    function getSuccess(data) {
        console.log("data=" + data);
        var trClone = $(".tr-clone");
        var jsonData = $.parseJSON(data);
        var count = 0;
        for (var key in jsonData) count++
        $.each(jsonData, function (key, value) {
            trClone.find(".title").val(value.Title);
            trClone.find(".work-type").val(value.WorkType);
            trClone.find(".form-type").val(value.FormType);
            trClone.find(".genre").val(value.Genre);
            console.log("value.FormType=" + value.FormType + ", form-type.val()=" + trClone.find(".form-type").val());
            console.log("value.Genre=" + value.Genre + ", genre.val()=" + trClone.find(".genre").val());
            trClone.find(".form-type").val(value.FormType);
            trClone.find(".nbr-pages").val(value.NumberOfPages);
            trClone.find(".synopsis a[href='" + value.Filename + "']");
            if (key === count - 1) return false;
            trClone = trClone.clone().insertAfter($(".tr-clone:last"));
        });
    }

的console.log

在JS代码中,JSON.parse(...)抛出下面的错误。

  

data = [{“Title”:“莫扎特,神童”,“0”:“莫扎特,   神童”, “WorkType”: “1”, “1”: “1”, “FormType”: “4”, “2”: “4”, “流派”: “12”, “3”: “12” “NumberOfPages”: “250”, “4”: “250”, “文件名”: “6532744220.pdf”, “5”: “6532744220.pdf”, “OriginalFilename”: “MozartWunderkindQueryLetter.pd”, “6” : “MozartWunderkindQueryLetter.pd”},{ “标题”:“莫扎特,   Wunderkind Query-Letter“,”0“:”莫扎特,神童   查询信 “ ”WorkType“: ”2“, ”1“: ”2“, ”FormType“: ”7“, ”2“: ”7“, ”流派“: ”9“, ”3“:” 9" , “NumberOfPages”: “129”, “4”: “129”, “文件名”: “9981287843.pdf”, “5”: “9981287843.pdf”, “OriginalFilename”: “MozartWunderkindQueryLetter.pd”,” 6 “:” MozartWunderkindQueryLetter.pd “}] [{” 标题 “:” 莫扎特,   神童 “ ”0“:” 莫扎特,   神童”, “WorkType”: “1”, “1”: “1”, “FormType”: “4”, “2”: “4”, “流派”: “12”, “3”: “12” “NumberOfPages”: “250”, “4”: “250”, “文件名”: “6532744220.pdf”, “5”: “6532744220.pdf”, “OriginalFilename”: “MozartWunderkindQueryLetter.pd”, “6” : “MozartWunderkindQueryLetter.pd”},{ “标题”:“莫扎特,   Wunderkind Query-Letter“,”0“:”莫扎特,神童   查询信 “ ”WorkType“: ”2“, ”1“: ”2“, ”FormType“: ”7“, ”2“: ”7“, ”流派“: ”9“, ”3“:” 9" , “NumberOfPages”: “129”, “4”: “129”, “文件名”: “9981287843.pdf”, “5”: “9981287843.pdf”, “OriginalFilename”: “MozartWunderkindQueryLetter.pd”,” 6 “:” MozartWunderkindQueryLetter.pd“}]

     

VM1161:1未捕获的SyntaxError:意外的令牌[在JSON中的位置   613n.parseJSON @jquery.min.js:4getSuccess @ VM1137:13(匿名   函数)@ VM1136:97j @jquery.min.js:2k.fireWith @jquery.min.js:2x   @jquery.min.js:4(匿名函数)@jquery.min.js:4

1 个答案:

答案 0 :(得分:1)

这里仔细查看你的JSON字符串我知道你正在回复字符串两次......所以它会被附加两次发送到客户端,这就是为什么它没有以正确的方式显示..

你可以使用JSON parser在线工具来了解你的JSON字符串....所以你需要弄明白你的PHP代码,为​​什么它被发送两次,它必须是像你这样的东西已经回应了两次......如果你把你的整个PHP代码,那么我们可以帮助你更多..

总而言之,您需要更正服务器的响应,因为JSON编码工作正常,编码字符串只应响应一次

BINGO !!!!在您的PHP代码中,您在行后执行switch case两次(!isset($ _ REQUEST [&#39; action&#39;])|| isEmpty($ _ REQUEST [&#39; action&#39;])),请参阅下面就是为什么它会回显两次......并破坏你的JSON字符串

if (!isset($_REQUEST['action'])  || isEmpty($_REQUEST['action']))
    throw new Exception('Programmer error: action not posted.');
else {
    $action = $_REQUEST['action'];
    switch($action) {
    case 'get-writer-data':
        getWritersData();
        break;
    case 'update-writers':
        select();
        break;
    default:
        throw new Exception("Unknown action: " . $action);
        break;
    }
}

if (!isset($_REQUEST['action'])  || isEmpty($_REQUEST['action']))
    throw new Exception('Programmer error: action not posted.');
else {
    $action = $_REQUEST['action'];
    switch($action) {
    case 'get-writer-data':
        getWritersData();
        break;
    case 'delete-writers':
        deleteWritersData();
        break;
    case 'update-writers':
        saveWritersData();
        break;
    default:
        throw new Exception("Unknown action: " . $action);
        break;
    }
}