【发布时间】:2012-09-19 06:21:45
【问题描述】:
我要做的是通过 Ajax 获取一个 json 对象,并使用一种值填充 Bootstrap Typeahead。
这是我的代码:
nameTypeHead: function () {
var _self = this,
searchInput = $('#nameTypeHead'),
arr = [];
function getArray() {
$.ajax({
url: '/Home/AutoComplete',
type: 'post',
dataType: 'json',
data: { searchText: searchInput.val() },
success: function (data) {
$.each(data, function () {
arr.push(this.Name);
});
return arr;
}
});
}
searchInput.typeahead({
source: getArray()
});
}
我收到 arr 为 null
的错误我也尝试了.parseJSON(),但没有成功:
$.each($.parseJSON(data), function () {
arr.push(this.Name);
});
如何在 Typeahed 中仅显示我的 Json 对象的值名称?
如果在 Ajax Success 中我输入 alert(JSON.stringify(data)); 它会正确提醒我的 Json 对象。
【问题讨论】:
-
success回调不必返回任何内容,因为它是一个异步调用 - 检查 this example instead。 -
另外,如果我删除
return arr;,它也不起作用... -
从你的链接我无法理解 CoffeeScript。我应该在哪里声明
property: "name"
标签: jquery ajax json twitter-bootstrap