【问题标题】:how to remove parsererror: SyntaxError: Unexpected token < in JSON at position 0如何删除解析器错误:SyntaxError: Unexpected token < in JSON at position 0
【发布时间】:2017-08-06 06:57:19
【问题描述】:

我正在尝试使用 PHP 从 MySQL 数据库中获取数据并将其作为 JSON 传递。当我尝试显示响应时,它显示错误 parsererror: SyntaxError: Unexpected token

jQuery:

$(document).ready(function()
{
    $("#display").change(function()
    {
        var type = document.getElementById('display').value;
        alert(type);
        $.ajax(
        {
            //create an ajax request to load_page.php
            type: "GET",
            url: "DBOperations.php",
            data : "type=" +type,
            dataType: "json",  //expect text to be returned                
            success: function(response)
            {                  
                //$("#response").html(response); 
                //alert(response.);

                $.each(response, function(index, element)
                {
                    $('#response').html($(
                    {
                        text: element.name
                    }));
                });
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                alert('error: ' + textStatus + ': ' + errorThrown);
            }
        });
    });
});

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();
    //echo 'Here: ' .$stmt;
    //$rows = $stmt->fetch();
    $rows = $stmt->fetchAll();
    foreach ($rows as $row)
    {
        echo "ClientID: ".$row['client_id'] . " ";
        echo "Name: ".$row['client_name'] . " ";
        echo "Title: ".$row['client_title'] . " ";
        echo "Client Type: ".$row['client_type'] . "<br>";
    }

    //Display associative array
    echo '<pre>';
    print_r($rows) .'<br>';
    header('Content-type: application/json');
    json_encode($rows);
    print_r(json_encode($rows));
}
catch (PDOException $ex)
{
    echo "There was a problem executing the Query: " . $ex->getMessage();
}

如果我尝试使用 alert() 检查我得到的响应是什么,它会显示:[object HTMLDivElement]

【问题讨论】:

  • 我已经评论了所有的回声,但错误仍然存​​在。
  • 您必须删除所有不是 json 的输出。查看命令行并查看那里输出的内容。它应该只是一个有效的 json
  • 我在 jQuery 中将数据类型更改为文本而不是 JSON,并且它起作用了。但在我的答案中显示如下输出。我需要获取数据并将其提供给另一个元素或表格。
  • 您的初始问题显然已经解决,无需这样做。对于第二个问题,请另开一个问题

标签: php jquery json


【解决方案1】:

删除带有 pre 标签的回声,它们会污染您的输出,结果不再是有效的 JSON。

【讨论】:

    【解决方案2】:

    你应该将json类型的字符串从php传递给jQuery,在你传递的字符串中显示一些html标签,删除foreach循环并回显json_encode($rows);

    你的代码应该是这样的:

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

    注意:php 输出在返回时不应有任何空格或空行,例如,如果 php 文件如下所示,则 jQuery json 解析器出错:

    <--- here empty line --->
    
    <?php
        echo json_encode($row);
    ?>
    
    <--- here empty line --->
    

    【讨论】:

      【解决方案3】:

      			$(document).ready(function()
                  {
                      $("#display").change(function()
                      {	var type = document.getElementById('display').value;
                          $.ajax(
                          {
                              type: "GET",
                              url: "check1.php",
                              data : {"type":type},             
                              success: function(response)
                              {        
      							var aa='';          				
      							var data = JSON.parse(response);	
      							 data.forEach(function(d){
      								aa+= d+'<br>';
      							 });
      							$('#response').html(aa); 
                              },
                              error: function(jqXHR, textStatus, errorThrown)
                              {
                                  alert('error: ' + textStatus + ': ' + errorThrown);
                              }
                          });
                      });
                  });
      <?php
      try
                          {
      						$type = $_GET['type'];
                              $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();
      						$ars=null;
                              foreach ($rows as $row)
                              {
      							$ars[] = $row['client_name'];
                              }
      						print_r(json_encode($ars));
                          }
                          catch (PDOException $ex)
                          {
                              echo "There was a problem executing the Query: " . $ex->getMessage();
                          }
                          ?>

      【讨论】:

        【解决方案4】:

        从 php 页面获取 json 时,只在页面上打印 json。

        尝试删除这部分

        echo'<pre>'; 
        print_r($rows).'<br>';
        

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-30
          • 2022-01-22
          • 1970-01-01
          • 2017-12-15
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多