jQueryUI自动完成JSON不返回预期数据 [英] jQueryUI autocomplete JSON not returning expected data

查看:88
本文介绍了jQueryUI自动完成JSON不返回预期数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQueryUI自动完成功能搜索MySQL数据库.当用户在搜索字段中按Enter键时,我想用从DB返回的结果填充div.

Using jQueryUI autocomplete to search a MySQL database. When user presses enter in the search field, I want to populate a div with the result(s) returned from DB.

该代码有效,并且确实返回建议的自动完成列表.

The code works and does return an autocomplete list of suggestions.

但是,在select:函数中返回的JSON数据不是我所期望的.

在下面的PHP代码示例中,查询从数据库请求与查询匹配的每个标题相关的所有字段.应该有其他字段,例如作者,出价,isbn,体裁等.但是,仅返回了title字段.

In the PHP code sample below, the query requests all fields from the database related to each title matched by the query. There should have been other fields, like author, bid, isbn, genre, etc. -- however, only the title field was returned.

Google Chrome浏览器的控制台如下:

Google Chrome's console looks like this:

Object {item: Object}
  item: Object
    label: "Much Obliged Jeeves"
    value: "Much Obliged Jeeves"
    __proto__: Object
  Object {label: "Much Obliged Jeeves", value: "Much Obliged Jeeves"}

其他字段在哪里?

我的jQuery:

$('#srxbks').autocomplete({
    source: "autocomplete_test.php",
    minLength: 1,
    select: function( event, ui ) {
        console.log(ui);
        console.log(ui.item);
        console.log(ui.item.label);

        //Not working:
        var out = 'Title: ' + ui.item.title + '<br>';
        out += 'Author: ' + ui.item.author + '<br>';
        $('.booksTableDIV').val(out);
    }
});

我的PHP:

<?php
include 'connect.php';

$term = strip_tags($_GET['term']);//retrieve search term sent by autocomplete

$qstring = "SELECT * FROM `books` WHERE `title` LIKE '%" .$term. "%'";
$query = mysql_query($qstring) or die(mysql_error());

while ($row = mysql_fetch_array($query)) {
    $row['title']=htmlentities(stripslashes($row['title']));
    $row['bid']=(int)$row['bid'];
    $row_set[] = $row['title'];
}
echo json_encode($row_set);

推荐答案

您只需要确保所有变量都包含在返回数组中即可.您的PHP是有问题的部分,您没有将变量正确地传输到JSON.您的jQuery很好.以下是您希望对要发送回jQuery的每个其他变量进行的操作.

You just need to be sure all your variables are included in the returning array. Your PHP is the part having an issue, your are not transferring the variables to JSON correctly. Your jQuery is fine. The following is what you need to do for each extra variable you wish to send back to your jQuery.

// Initialize your variables here
$returns = array();
$i = 0;

while ($row = mysql_fetch_array($query)) {
    // Format your variables here
    $row['title']=htmlentities(stripslashes($row['title']));
    $row['bid']=(int)$row['bid'];

    // Enter results into JSON array here
    $returns[$i]['title'] = $row['title'];
    $returns[$i]['bid'] = $row['bid'];
    $i++;
}

echo json_encode($returns);

这篇关于jQueryUI自动完成JSON不返回预期数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆