我正在使用symfony sfFormExtra插件附带的jquery自动完成插件。
/*
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/
它似乎根据键排序json结果,但我在代码中找不到任何提及排序选项。
我希望结果排序,就像从服务器返回一样。
结果就像这样构建
public function doMemberSelectForSelectById($q, $limit){
$query = $this->retrieveMemberOrganisations($this->createUnrestrictedQuery('o'))->
andWhere("o.name like '%".$q."%'")->
orderBy("o.name")->
limit(intval($limit));
$org_data = $query->execute();
$orgs = array();
foreach ($org_data as $org){
$orgs[$org->getId()] = $org->getName();
}
return $orgs;
}
$orgs = Doctrine_Core::getTable('Organisation')->
doMemberSelectForSelectById($request->getParameter('q'), $request->getParameter('limit'));
echo $this->renderText(json_encode($orgs));
}
return sfView::NONE;
Chrome开发者工具的结果是(按名称排序)
{
"1781": "1st Mechanical \/ 1st Maintenance",
"1771": "Acco Building Ltd",
"203": "Active Welding Limited",
"443": "Aircon Commissioning & Services Ltd",
"588": "Akon Electrical Engineering Limited",
"625": "Alaska Interiors Ltd",
"796": "Alutech Windows & Doors Ltd",
"584": "Arrow International Ltd"....
}
触发它的javascript就在这里
jQuery(document).ready(function() {
jQuery("#autocomplete_rsvpCompany1").focus(function({
jQuery(this).val('');});
jQuery("#autocomplete_rsvpCompany1").autocomplete(
'http://www.nzgbc.org.nz/index.php?option=com_nzgbc_member&uri=%2Forganisation%2FjsonListMember%2Faction',
jQuery.extend({}, {
dataType: 'json',
minChars: 0,
delay:0,
max:700,
scroll: true,
parse: function(data) {
var parsed = [];
for (key in data) {
parsed[parsed.length] = { data: [ data[key], key ], value: data[key], result: data[key] };
}
return parsed;
}
}, { })
).result(function(event, data) {
jQuery('#rsvpCompany1').val(data[1]);
});
我怎样才能做到这一点?
答案 0 :(得分:1)
您应该按如下方式更改“解析”方法:
parse: function(data) {
var parsed = [];
for (key in data) {
parsed[parsed.length] = {
data: [ data[key], key ],
value: data[key],
result: data[key]
};
}
parsed.sort(function (a, b){
var aKey = a.value;
var bKey = b.value;
return ((aKey < bKey) ? -1 : ((aKey > bKey) ? 1 : 0));
});
return parsed;
}
问题是“data”数组有一个数字键,所以当你循环“for”循环中的“data”元素时,你会按照数字顺序将元素添加到“parsed”数组中(例如:203,443,584,588等),所以在将所有元素添加到“已解析”数组后,您必须按“data [key]”排序,而不是“key”。