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.

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

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: