我有一个 php/mysql 后端和一个 bootstrap/jQ 前端。还有 4 小时的头痛。
表单元素如下所示:
<input id="location_name" name="location_name" data-provide="typeahead"
autocomplete="off" type="text" placeholder="Location name"
class="input-xlarge" required="yes" value="" />
jQuery 看起来像这样:
$(document).ready(function(){
$('#location_name').typeahead({
'source': function (query,typeahead) {
var id = $("#area_id option:selected").attr('value');
return $.get(
'/app/event/location_name_typehead.php',
{ 'location_name': encodeURIComponent(query), 'area_id' : id },
function (data) { return data; }
);
},
'items': 4,
'minLength': 2
});
});
PHP看起来像这样:
<?php
header('Content-type: text/json');
$location_name = $_REQUEST['location_name'];
$area_id = $_REQUEST['area_id'];
//print_r($_REQUEST);
// ... PDO setup ...
$locations = $location_recs->fetchAll(PDO::FETCH_ASSOC);
if(count($locations) == 0) {
echo '[]';
} else {
foreach ($locations as $location) {
$names[] = $location['location_name'];
}
echo '[ "'.implode('", "', $names).'" ]';
};
?>
我已经尝试将 'application/json' 和 'text/json' 作为返回类型,并使用typeahead.process(data)
jQuery json 解码数据的变体来让该死的东西正常工作。正在返回搜索结果,即在字段中键入会触发 ajax 调用,并且返回的文档看起来是正确的:
[ "Administration Block", "Science Block" ]
谁能指出阻止它的明显(我假设)语法问题?