【发布时间】: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,并且它起作用了。但在我的答案中显示如下输出。我需要获取数据并将其提供给另一个元素或表格。
-
您的初始问题显然已经解决,无需这样做。对于第二个问题,请另开一个问题