我只是试图查询数据库并显示结果jquery的ajax方法,但如果我将dataType属性作为json,它只记录只有一个对象的结果,以下是我的代码:
//this is a method is an object which will be triggered after a selection was made
lister: function () {
//this is to target the object as it is inside an event
var self = users;
//the ajax call
$.ajax({
url: 'index.php',
type: 'POST',
data: self.config.form.serialize(),
//this is the dataType
dataType: 'json',
success: function (results) {
//this for logging the result
console.log(results);
}
});
}
php代码
if(isset($_POST['q']) && !empty($_POST['q'])){
$na = $_POST['q'];
$query = mysql_query("SELECT id,first_name, last_name
FROM users WHERE users.first_name LIKE '$na%'");
$num=mysql_num_rows($query);
if($num >= 1){
while($row = mysql_fetch_array($query)){
//encoding the result as json
echo json_encode($row);
}
} else{
echo "no results found ";
}
//here we return so it won't display all of the pages
return;
}
答案 0 :(得分:1)
您正在生成无效的JSON。您正在独立编码表的每一行,生成如下内容:
{"foo": "bar"}{"foo": "bar"}{"foo": "bar"}
这是无效的。它只是对象的串联。你需要的是一个对象数组:
[{"foo": "bar"}, {"foo": "bar"}, {"foo": "bar"}]
您可以通过先创建一个数组,将每一行添加到它并对数组进行编码来实现:
$data = array();
while(...) {
$data[] = $row;
}
echo json_encode($data);
另一个问题是,如果没有找到结果,您只需返回纯文本,而不是JSON。这可能会导致客户端出错。如果你告诉jQuery期望JSON,那么每个可能的响应必须是JSON。所以你可能想要这样的东西:
echo json_encode(array('error' => 'no results found'));
甚至更好,返回一个空数组:
echo json_encode(array());
如果返回一个空数组,客户端应该很明显没有找到结果。