简体   繁体   English

jQuery AJAX无法解析来自PHP PDO方法的响应

[英]JQuery AJAX unable to Parse response from PHP PDO method

I am trying to fill a drop down list using JQuery AJAX and PHP. 我正在尝试使用JQuery AJAX和PHP填充下拉列表。 I have created a method in PHP which echo es a json_encoded() array . 我已经在PHP中创建了一个echo json_encoded() array However, when the document is loaded it fails to get the result because of some JSON parsing error. 但是,由于某些JSON解析错误,在加载文档时无法获得结果。

I am using a callable stored procedure in PHP and verified that it returns the correct result set when I tested the stored procedure in MySQL Workbench. 我在PHP中使用可调用的存储过程,并在我在MySQL Workbench中测试存储过程时验证了它返回了正确的结果集。

What could be causing this? 是什么原因造成的?

Error: 错误:

Parsing JSON Request Failed 解析JSON请求失败

RoleDaoImpl.php RoleDaoImpl.php

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());
    }
}

get_all_roles.php get_all_roles.php

require_once '../../core/init.php';
$roleDaoImpl = new RoleDaoImpl($pdo);

$roleDaoImpl->getAllRoles();

JS file JS文件

$(document).ready(function(){
    loadRolesToDropDown();
});

function loadRolesToDropDown(){
    var url = 'get_all_roles.php';
    $.ajax({
        url: url,
        type: 'post',
        dataType: 'json',
        success: function(response){
            var len = response.length;
            alert(response);
            $("#roledropdown").empty();
            for(var i = 0; i < len; i++){
                var roleId = response[i]['roleId'];
                var roleName = response[i]['roleName'];
                $("#roledropdown").append("<option value='"+roleId+"'>"+roleName+"</option>");
            }
        },
        error : function(x,e){
            if (x.status==0) {
                alert('You are offline!!\n 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.\nParsing JSON Request failed.');
            } else if(e=='timeout'){
                alert('Request Time out.');
            } else {
                alert('Unknown Error.\n'+x.responseText);
            }
        }
    });
}

I can't think of other ways to identify the cause. 我想不出其他方法来找出原因。 I'm fairly new with using AJAX with PHP. 我对将AJAX与PHP结合使用还很陌生。 I'm using AJAX to avoid refreshing the page. 我正在使用AJAX来避免刷新页面。 Recently, I tried to follow some tutorials and still trying to get a grasp of how JQuery Ajax and PHP work together. 最近,我尝试遵循一些教程,并且仍然试图了解JQuery Ajax和PHP如何协同工作。

What other troubleshooting can I do? 我还能做其他什么故障排除?

I'd appreciate any suggestion. 我将不胜感激任何建议。

Thank you. 谢谢。

***** EDIT ****** *****编辑******

I tried printing log using console.log() as in: 我尝试使用console.log()打印日志,如下所示:

success: function(response){
    var len = response.length;
    alert(response);
    console.log(response);
    $("#roledropdown").empty();
    for(var i = 0; i < len; i++){
        var roleId = response[i]['roleId'];
        var roleName = response[i]['roleName'];
        $("#roledropdown").append("<option value='"+roleId+"'>"+roleName+"</option>");
    }
}

I get the ff on Google Chrome's console window. 我在Google Chrome浏览器的控制台窗口中看到了ff。

jquery-3.3.1.js:9488 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. jquery-3.3.1.js:9488 [不推荐使用]不赞成在主线程上使用同步XMLHttpRequest,因为它对最终用户的体验具有不利影响。 For more help, check https://xhr.spec.whatwg.org/ . 如需更多帮助,请访问https://xhr.spec.whatwg.org/

在此处输入图片说明

Then, I inspected the this line ajax @jquery-3.3.1.js:9206 . 然后,我检查了此行ajax @jquery-3.3.1.js:9206 And I get the ff. 而我得到了。 ( I don't know if it has something to do with parsing ) 我不知道是否与解析有关

try {
    completed = false;
    transport.send( requestHeaders, done );
    } catch ( e ) {
    // Rethrow post-completion exceptions
    if ( completed ) {
        throw e;
    }

    // Propagate others as results
    done( -1, e );
}

By the way, the drop down list is contained in a modal div . 顺便说一下,下拉列表包含在模式div I'm not sure if it has anything to do with the error. 我不确定是否与错误有关。 Something seemed to be deprecated as per the message shown in console window. 根据控制台窗口中显示的消息,似乎已弃用某些内容。

****** END OF EDIT ****** ******编辑结束******

如果怀疑json_encode()问题,则必须检查该函数是否返回false,然后使用json_last_error()了解原因。

I cannot speak to your PHP output, but using placeholder data, I can easily confirm your JS does what you expect it to do. 我无法说出您的PHP输出,但是使用占位符数据,我可以轻松地确认您的JS达到了您的期望。 Below is your JS implemented using data from https://jsonplaceholder.typicode.com/users . 以下是使用https://jsonplaceholder.typicode.com/users中的数据实现的JS。 It works as expected. 它按预期工作。

This indicates the output from your server is incorrect. 这表明服务器的输出不正确。 You can use the browser's developer tools to determine precisely what is being sent back from the server using the network tab. 您可以使用浏览器的开发人员工具来精确确定使用“网络”标签从服务器发回的内容。 The image demonstrates this on this snippet. 该图像在此片段上对此进行了演示。

在此处输入图片说明

 $(document).ready(function(){ loadRolesToDropDown(); }); function loadRolesToDropDown(){ var url = 'https://jsonplaceholder.typicode.com/users'; $.ajax({ url: url, type: 'get', dataType: 'json', success: function(response){ var len = response.length; $("#roledropdown").empty(); for(var i = 0; i < len; i++){ var id = response[i]['id']; var name = response[i]['name']; $("#roledropdown").append("<option value='"+id+"'>"+name+"</option>"); } }, error : function(x,e){ if (x.status==0) { alert('You are offline!!\\n 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.\\nParsing JSON Request failed.'); } else if(e=='timeout'){ alert('Request Time out.'); } else { alert('Unknown Error.\\n'+x.responseText); } } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="roledropdown"></select> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM