0

我有一个 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" ]

谁能指出阻止它的明显(我假设)语法问题?

4

1 回答 1

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);
    });
},
于 2013-08-22T19:28:56.073 回答