【问题标题】:How to access returned JSON's values on auto complete selection?如何在自动完成选择中访问返回的 JSON 值?
【发布时间】:2015-05-07 17:13:57
【问题描述】:

我有服务器通过在文本框中输入的一些关键字返回的这种 JSON 格式:

[{"id":1,"value":"some string!"}]

我希望当用户选择一个项目时,浏览器使用选择的id 导航到另一个页面;它存在于返回的 JSON 中。这是我的自动完成代码:

$(function () {

$("#search-box").autocomplete({
    source: function (request, response) {
        $.ajax({
            type: "GET",
            url: "../Contenthandler/Search.ashx",
            dataType: "json",
            data: 'query=' + request.term,
            success: function (data) {
                response($.map(data, function (item) {
                    return { label: item.value };
                })
       );

            }
        });
    },
    minLength: 3,
    open: function () {
        $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
    },
    close: function () {
        $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
    },
    select: function (event, ui) {
        if (ui.item) {
            window.location.href = "../ControlPanel.aspx?id=" + ui.item.id;
        }
    }
 });

});

ui.item.idundefined。如何在选择活动中访问id(1)?

【问题讨论】:

  • 根据您的 json 结果示例,最外面的数据元素是一个数组。因此,此时您需要使用数组表示法进行引用。
  • @Taplar 所以,我怎样才能访问id
  • 您收到回复了吗?换句话说,您的success 处理程序是否曾被调用过? @Taplar 的观点是结果对象 isnt json 但您的 ajax 调用期待 json 响应。
  • 如果 ui 是您的基本 json 元素,它将是 ui[0].id,或者如果 item 是基本元素,它将是 ui.item[0].id 。 console.log() 无论您使用什么变量来查看它的结构。
  • @Taplar 如果 OP 已经在 UI 中获得选择...为什么 ajax 会成为问题?

标签: javascript jquery json jquery-ui autocomplete


【解决方案1】:

您没有 id 作为您映射到数组的对象的属性,并在您的 ajax 成功中传递给自动完成。

您的对象只有一个属性label。添加您需要的其他属性或仅使用 label 属性扩展您的响应对象

 response($.map(data, function (item) {
       return { label: item.value, id : item.id };// add "id" property
  });

实际上,如果从服务器返回的数据是最重要的结构......你不需要做任何映射。你也真的不需要自己的 ajax 并且可以将服务器路径直接连接到插件。

查看将 url 路径设置为源的演示和文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多