duanqian6982 2014-01-11 20:47
浏览 57
已采纳

在jQueryUI自动完成回调中访问JSON响应数据

I am 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.

However, I cannot understand how to use the JSON data returned in the select: function, for example to access the title and author fields returned in the JSON object. See the indicated alert() line in the jQuery code sample.

ui.item alerts as [object Object]

ui.item.title alerts as undefined.

What else can I try?
Also, is item the correct label to use? If so, why? Where does that come from (I used item because it was consistently used in several examples I reviewed.)

My jQuery:

$('#srxbks').autocomplete({
    source: "autocomplete_test.php",
    minLength: 1,
    select: function( event, ui ) {
        alert('You chose: ' + ui.item);   <=== THIS LINE <===
        var out = 'Title: ' + ui.item.title + '<br>';
        out += 'Author: ' + ui.item.author + '<br>';
        $('.booksTableDIV').val(out);
    }
});

My 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);
  • 写回答

1条回答 默认 最新

  • duanpu1064 2014-01-11 20:55
    关注

    It's hard to give an exact answer without knowing what the JSON response is.

    Alert isn't a good way to view javascript objects as you noticed. Try using console.log to inspect the object in the browser's developer console. This will help you find the right syntax.

    To access the developer console...

    • ... in Chrome, in the menu, go to View > Developer Tools
    • ... in Firefox, in the menu, go to Tools > Web Developer > Web Console
    • ... in IE, ... not sure... I'm on a Mac right now. It should be something like the above. I think it is also accessible by F12

    In each of those, there should be a console tab to view log messages recorded using console.log.

    I suspect that you will just need to do something like ui.item[0] or ui.item.title... but again, I cant be sure without the JSON data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向