【问题标题】:Getting JSON encoded values in AJAX在 AJAX 中获取 JSON 编码值
【发布时间】:2020-06-29 03:59:01
【问题描述】:

我正在从数据库中检索数据。当我尝试使用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]);
            //}
        }
    })
})

任何帮助将不胜感激:)

【问题讨论】:

  • 使用您的浏览器开发工具(网络面板)检查请求的实际回答。
  • 您的数据库查询可能没有返回任何记录,因为您正在将输入的值与 string 进行比较。如果您想在 中以名称 deptCode 查找它,那么当然需要去掉引号。

标签: javascript php sql json ajax


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-10-25
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 2015-09-26
    • 2019-05-10
    • 2017-10-12
    • 1970-01-01
    相关资源
    最近更新 更多