我有一个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" ]
有人能指出明显(我假设)语法问题正在阻止吗?
答案 0 :(得分:1)
您无法从AJAX调用中返回任何内容。它们是异步的,您需要执行与回调中的数据相关的任何事情。
此外,typeahead希望source
函数返回一个数组或调用作为第二个参数传递的函数。在你的情况下,你不能返回任何东西,因为它是异步的,所以你需要使用第二个参数。
'source': function (query,typeahead) {
var id = $("#area_id option:selected").attr('value');
$.get('/app/event/location_name_typehead.php', {
'location_name': encodeURIComponent(query),
'area_id': id
}, function(data){
typeahead(data);
});
},