无法使用jQuery和AJAX在表中显示JSON数据

时间:2017-08-06 09:50:57

标签: php jquery json ajax

我正在尝试将使用PHP从MySQL数据库中获取为JSON的数据显示为HTML元素(例如表格)。以下是我的代码:

<!DOCTYPE html>
<html>
    <head>
        <title>Test Ajax</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                $("#display").change(function()
                {
                    var type = document.getElementById('display').value;
                    $.ajax(
                    {
                        //create an ajax request to load_page.php
                        type: "POST",
                        url: "DBOperations.php",
                        data : "type=" +type,
                        dataType: "text",  //expect text to be returned                
                        success: function(response)
                        {
                            var tr = $('<tr>');
                            tr.append('<td>' + response.client_id + '<td>');
                            tr.append('<td>' + response.client_name + '<td>');
                            tr.append('<td>' + response.client_title + '<td>');
                            tr.append('<td>' + response.client_type + '<td>');

                            $('#myTable').append(tr);
                        },
                        error: function(jqXHR, textStatus, errorThrown)
                        {
                            alert('error: ' + textStatus + ': ' + errorThrown);
                            alert(response);
                        }

                    });
                });
            });
        </script>
    </head>
    <body>
        <form>
            <select id="display" name="clienttype" onchange="showClient(this.value)">
            <option value="">Select a Client:</option>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
            <option value="D">D</option>
            </select>
            </form>
            <br>
        <table id="myTable">
            <tr>
                <th>ClientID</th>
                <th>ClientName</th>
                <th>ClientTitle</th>
                <th>ClientType</th>
            </tr>
        </table>
        </form>
    </body>
</html>

以下是我从php获得的JSON:

[{"client_id":"1","0":"1","client_name":"asdf","1":"asdf","client_title":"asdf","2":"asdf","client_type":"a","3":"a"}]

此外,如果我将AJAX中的数据类型设置为json,它会显示此问题中的错误: how to remove parsererror: SyntaxError: Unexpected token < in JSON at position 0

所以我把它保存为html或文本,至少显示错误的响应。但我需要格式化响应并将其提供给另一个元素。

提前致谢。

2 个答案:

答案 0 :(得分:0)

    $.ajax(
                        {
                            //create an ajax request to load_page.php
                            type: "POST",
                            url: "DBOperations.php",
                            data : {"type :" +type},
                            dataType: "text",  //expect text to be returned                
                            success: function(response)
                            {
    		var data = response.d;
                                var tr = $('<tr>');
                                tr.append('<td>' + data .client_id + '<td>');
                                tr.append('<td>' + data.client_name + '<td>');
                                tr.append('<td>' + data.client_title + '<td>');
                                tr.append('<td>' + data.client_type + '<td>');
    
                                $('#myTable').append(tr);
                            },
                            error: function(jqXHR, textStatus, errorThrown)
                            {
                                alert('error: ' + textStatus + ': ' + errorThrown);
                                alert(response);
                            }
    
                        });
    
try this one.

答案 1 :(得分:0)

首先,如果您期望从服务器返回JSON字符串,那么您应该将dataType: "json"放入AJAX请求中。其次,您的success回调函数应该是这样的:

success: function(response){
    var tr = $('<tr>');
    tr.append('<td>' + response[0].client_id + '<td>');
    tr.append('<td>' + response[0].client_name + '<td>');
    tr.append('<td>' + response[0].client_title + '<td>');
    tr.append('<td>' + response[0].client_type + '<td>');
    $('#myTable').append(tr);
}

更新(1):

基于您共享的the question link,您可以清楚地看到您正在以错误的方式创建和输出json字符串,PHP和AJAX代码应该是这样的:

PHP代码:

try{
    $dsn = 'mysql:host=localhost;dbname=practice_db'; //your host and database name here.
    $username = 'root';
    $password = '';

    //Connect to database
    $conn = new PDO($dsn, $username, $password);
    $query = "SELECT * FROM client WHERE client_type = :client_type";

    //Prepare and Execute Query
    $stmt = $conn->prepare($query);    
    $stmt->bindParam(':client_type', $type);
    $stmt->execute();
    $rows = $stmt->fetchAll();
    echo json_encode($rows);
}catch (PDOException $ex){
    echo "There was a problem executing the Query: " . $ex->getMessage();
}

AJAX代码:

$.ajax({
    type: "POST",
    url: "DBOperations.php",
    data : "type=" + type,
    dataType: "json",         
    success: function(response){
        $.each(response, function(key,value) {
            var tr = $('<tr>');
            tr.append('<td>' + value.client_id + '<td>');
            tr.append('<td>' + value.client_name + '<td>');
            tr.append('<td>' + value.client_title + '<td>');
            tr.append('<td>' + value.client_type + '<td>');

            $('#myTable').append(tr);
        }); 
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert('error: ' + textStatus + ': ' + errorThrown);
        alert(response);
    }

});