【问题标题】:Cannot display JSON data in a table using jQuery and AJAX无法使用 jQuery 和 AJAX 在表中显示 JSON 数据
【发布时间】:2017-08-06 09:50:57
【问题描述】:

我正在尝试将使用 PHP 从 MySQL DB 获取的 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 或文本,至少显示没有错误的响应。但我需要格式化响应并将其提供给另一个元素。

提前致谢。

【问题讨论】:

    标签: php jquery json ajax


    【解决方案1】:

        $.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.

    【讨论】:

      【解决方案2】:

      首先,如果您希望从服务器返回一个 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);
      }
      

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

      【讨论】:

      • 如果我将数据类型更改为 json,则会显示错误:parsererror: SyntaxError: Unexpected token
      • @JunaidFarooq 您可能正在回显/发送除 JSON 字符串之外的其他内容,请检查。您是否按照建议的解决方案更改了 success 回调函数?
      • 是的,我已根据您提出的解决方案更改了成功回调,但它不起作用。您可以通过提供的链接检查我的 PHP 代码和相关的 JSON 错误。
      • @JunaidFarooq 你的 PHP 代码在哪里?我没有看到任何与您的 PHP 页面相关的链接。顺便说一句,除了 that json 字符串之外,您是否检查过 echoing 其他内容?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 2014-10-29
      • 2018-10-29
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多