在Ajax中获取json编码的值

问题描述 投票:0回答:1

我正在从数据库中检索数据。当我尝试使用console.log(response)在控制台中将其输出时,我将得到以下信息:

Array
(
    [deptCode] => Econ
    [collegeCode] => BA
    [deptName] => Economics
)

我期望得到值Econ, BA, and Economics

我的问题是,当我使用response["deptCode"]将它从PHP传递到ajax时,我会得到undefined

我尝试做data = JSON.parse(response);,但会收到错误:

Uncaught SyntaxError: Unexpected token A in JSON at position 0
   at JSON.parse (<anonymous>)

我也尝试过:

for(var key in response){
    console.log(response[key]);
}

但是结果是这样的:image result from console

这是我的db.php:

public function getDept($code){
        $sql = 'SELECT * FROM department WHERE "deptCode" = :code';
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['code'=>$code]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result;

action.php:

if(isset($_POST['edit_id'])){
    $id = $_POST['edit_id'];

    $row = $db->getDept($id);
    echo json_encode($row);
}

索引:

$("body").on("click", ".editBtn", function(e){
                e.preventDefault();
                edit_id = $(this).attr('id');
                $.ajax({
                    url: "action.php",
                    type: "POST",
                    data:{edit_it:edit_id},
                    success:function(response){
                        console.log(response);
                        //data = JSON.parse(response);
                        //for(var key in response){
                        //    console.log(response[key]);
                        //}
                    }
                })
            })

任何帮助将不胜感激:)

javascript php json ajax
1个回答
0
投票
我以前有json_decode,例如错误。要在ajax响应中解析为JSON,您必须在PHP中解码数据。即,请在PHP中使用“ json_decode”。然后在ajax响应中使用JSON.parse(response)。希望您能解决。
© www.soinside.com 2019 - 2024. All rights reserved.