目前正致力于jQuery自动完成,我可以从JSON单列数据生成数据,但我希望两个值应该显示标签和descirption
这是我的json
[{"id":"Emirates College of Technology- UAE","label":"COL000001","value":"COL000001"}, {"id":"Al Khawarizmi nternational ollege- UAE","label":"COL000002","value":"COL000002"}, {"id":"Syscoms ollege","label":"COL000003","value":"COL000003"}, {"id":"Abounajm Khanj Pre-Uni enter","label":"COL000004","value":"COL000004"}, {"id":"Advanced lacement","label":"COL000005","value":"COL000005"}, {"id":"Al Buraimi College Uni Clge)","label":"COL000006","value":"COL000006"}, {"id":"Al-Ain Community ollege","label":"COL000007","value":"COL000007"}, {"id":"AMA Computer ollege","label":"COL000008","value":"COL000008"}, {"id":"Arab Academy for Bankg nd Fin","label":"COL000009","value":"COL000009"}, "id":"ARABACDSCITECHMARTIMETRNS","label":"COL0000010","value":"COL0000010"}, "id":"Arapahoe Community College","label":"COL0000011","value":"COL0000011"}, {"id":"Other","label":"Other","value":"Other"}]
这是我的jquery代码
$("#scl_name").autocomplete({
highlightClass: "bold",
source: function( request, response ) {
var regex = new RegExp(request.term, 'i');
//var filteredArray = filteredArray.slice(0,10);
$.ajax({
url: "json/dummy.json",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data, function(item) {
if(regex.test(item.label)){
var html="";
html += "<table>";
html += " <tr>";
html += " <td>"+addslashes(item.label)+"</td>";
html += " <td>"+addslashes(item.id)+"</td>";
html += " </tr>";
html += "</table>";
return {
value: html,
value: item.id,
value: item.label
};
}
}));
},
});
},
select: function(event, ui) {
$('#school_Name').val(ui.item.id);
}
});
});
function addslashes(string) {
return string.replace(/\\/g, '\\\\').
replace(/\u0008/g, '\\b').
replace(/\t/g, '\\t').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/'/g, '\\\'').
replace(/"/g, '\\"');
}
使用上面的代码,我得到的数据是第一列,但不是第二列的第二列,我得到的值是未定义的
我在这里做错了什么?
ReferenceError: Item is not defined
html += " <th>" + Item + "</th>";
答案 0 :(得分:3)
嗯,这是我的帮助。如果你可以确定你正在接收你期望的东西,首先处理JSON会更好。为此,您在AJAX响应中有一个名为.success的函数,它会解析每个JSON项目(这将是您的第一个项目:{&#34; id&#34;:&#34;阿联酋科技大学 - 阿联酋&#34 ;,&#34;标签&#34;:&#34; COL000001&#34;&#34;值&#34;:&#34; COL000001&#34;})
为了确保您收到了id,label和value元素,我将在您的成功函数中执行以下操作:
的console.log(item.id);
console.log(item.label);
console.log(item.value);
或直接
console.log(item); // this will be presented as an object you can examine on your chrome browser, for example.
如果您确定要在客户端上获取值,那么我将解决您从函数返回时遇到的问题,因为您可能知道您只能返回一个值,而不是三个:
return {
value: html,
value: item.id,
value: item.label
};
将其更改为:
return {
value: html,
};
因为你似乎已经创造了整个价值。如果这不是您的问题,请再次回复。
如果您想添加标题,可以这样做:
var html = "";
html += "<table>";
html += " <tr>";
html += " <th>" + Title + "</th>";
html += " <th>" + Description + "</th>";
html += " </tr>";
html += " <tr>";
html += " <td>" + addslashes(item.label) + "</td>";
html += " <td>" + addslashes(item.id) + "</td>";
html += " </tr>";
html += "</table>";