JSON数据的格式:
{"users":[
{"uid":"123","displayName":"User 123","mail":"[email protected]"},
{"uid":"456","displayName":"User 456","mail":"[email protected]"},
{"uid":"789","displayName":"User 789","mail":"[email protected]"},
]}
或者
{[
{"uid":"123","displayName":"User 123","mail":"[email protected]"},
{"uid":"456","displayName":"User 456","mail":"[email protected]"},
{"uid":"789","displayName":"User 789","mail":"[email protected]"},
]}
在服务器端,在返回数据时一定要设置编码,否则会出错:
//设置编码,这句最重要
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// 设置浏览器不要缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
String json = "";
response.getWriter().println(json);
在客户端是用JQuery接收JSON数据:
$("#id").autocomplete("url",{
delay:10,//延迟10秒
max:5,//最多5条记录
minChars:1,
matchSubset:1,
matchContains:1,
cacheLength:10,
matchContains: true,
scrollHeight: 250,
width:250,
dataType:'json',//返回的数据类型为JSON类型
parse:function(data) {//解释返回的数据,把其存在数组里
var parsed = [];
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
value: data[i].itemid,
result: data[i].itemid //返回的结果显示内容
};
}
return parsed;
},
formatItem: function(item) {//显示下拉列表的内容
return "<div>"+item.itemid + " " + item.name+"</div>";
},
formatMatch: function(item) {
return item.itemid;
},
formatResult: function(item) {
return item.itemid;
}
}).result(function(event, item, formatted) {//把返回的结果内容显示在其他文本框上
$("#ortherid").val(item.name);
});
如果大家有什么不懂的,可以留言提问,我会尽我地能力为大家解答。