dsdzvprlp51692469 2018-05-14 08:19
浏览 130

正确解析Ajax的php对象数组的方法

I am trying to fill a dropdown using Ajax and PHP with JQuery. For some reason, I always get a Parse JSON Error.

JS file

function loadRolesToDropDown() {
    var url = 'controller/get_all_roles.php';
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'JSON',
        success: function (data) {
            var len = data.length;
            $("#roledropdown").empty();
            for (var i = 0; i < len; i++) {
                var roleId = data[i]['roleId'];
                var roleName = data[i]['roleName'];
                $("#roledropdown").append("<option value='" + roleId + "'>" + roleName + "</option>");
            }
        },
        error: function (x, e) {
            if (x.status == 0) {
                alert('You are offline!!
 Please Check Your Network.');
            } else if (x.status == 404) {
                alert('Requested URL not found.');
            } else if (x.status == 500) {
                alert('Internal Server Error.');
            } else if (e == 'parsererror') {
                alert('Error.
Parsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknown Error.
' + x.responseText);
            }
        }
    });
}

get_all_roles.php

$roleDaoImpl = new RoleDaoImpl($pdo);

$roleDaoImpl->getAllRoles();

Implementation of getAllRoles()

function getAllRoles()
{
    $roleList[] = "";
    try {
        $SQL = "CALL getAllRoles()";
        $sp_getAllRoles = $this->connection->prepare($SQL);
        $sp_getAllRoles->execute();
        $resultSet = $sp_getAllRoles->fetchAll(PDO::FETCH_ASSOC);
        foreach ($resultSet as $row) {
            $roleId = $row['role_id'];
            $roleName = $row['role_name'];
            $roleList[] = array("roleId" => $roleId, "roleName" => $roleName);
        }
        echo json_encode($roleList);
    } catch (PDOException $e) {
      die($e->getMessage());
    }
}

And when I tried to echo what's return by json_encode($roleList); I get the ff:

["",{"roleId":1,"roleName":"Administrator"},{"roleId":2,"roleName":"Teacher"},{"roleId":3,"roleName":"Student"}]

What is the correct way to parse the php object array return by php?

Thank you.

  • 写回答

2条回答 默认 最新

  • dongpao9437 2018-05-14 08:22
    关注

    In your php function getAllRoles

    function getAllRoles()
    {
        $roleList[] = ""; // -> should be $roleList = [];
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料