如何删除parsererror:SyntaxError:意外的标记<在位置0的JSON中

时间:2017-08-06 06:57:20

标签: php jquery json

我正在尝试使用PHP从MySQL数据库中获取数据并将其作为JSON传递。当我尝试显示响应时,它会显示错误parsererror:SyntaxError:Unexpected token<在JSON的第0位。有人可以帮忙。 下面是我的jQuery和PHP代码:

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]

4 个答案:

答案 0 :(得分:0)

使用 pre 标记删除回声,这些标记会污染您的输出,结果不再是有效的JSON。

答案 1 :(得分:0)

你应该将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 --->

答案 2 :(得分:0)

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

尝试删除此部分

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

希望这有帮助。

答案 3 :(得分:0)

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