【发布时间】: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.id 是undefined。如何在选择活动中访问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