在official example自动完成后,我想出了这个。
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: "/search",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.username, function (item) {
return {
label: item.name,
value: item.name
};
}));
},
error: function (data) {
}
});
},
minLength: 2,
select: function (event, ui) {
},
});
但是,我从未点击success: function (data) { .. }
但始终点击error: function (data) {
。
Firebug显示错误:"parsererror", SyntaxError: invalid label
/search
url在服务器端产生这个:
def search():
data = None
if 'name_startsWith' in request.args:
q = request.args['name_startsWith']
data = User.query(ndb.AND(User.firstname >= q, User.firstname <= q + u'\ufffd')).fetch(12)
js = []
for user in data:
js.append({'name' : user.fullname()})
return jsonify(username=js)
有什么建议吗?
答案 0 :(得分:1)
将数据类型更改为json
,因为您的响应是一个json对象,并且请求被发送到同一个域,因此不需要jsonp
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: "/search",
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.username, function (item) {
return {
label: item.name,
value: item.name
};
}));
},
error: function (data) {
}
});
},
minLength: 2,
select: function (event, ui) {
},
});