首页 > 解决方案 > 在 AJAX 中获取 JSON 编码值

问题描述

我正在从数据库中检索数据。当我尝试使用在控制台中输出它时console.log(response),我会得到这个:

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

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

我的问题是当我使用 将它从 PHP 传递到 AJAX 时response["deptCode"],我会得到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]);
}

但结果是这样的: 来自控制台的图像结果

这是我的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;

动作.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]);
            //}
        }
    })
})

任何帮助,将不胜感激 :)

标签: javascriptphpsqljsonajax

解决方案


json_decode之前有过这样的错误。要在 ajax 响应中解析为 JSON,您必须在 PHP 中解码数据。即请json_decode在 PHP 中使用。然后JSON.parse(response)在ajax响应中。我希望你能解决它。


推荐阅读