Typeahead/Bloodhound Remote未返回数据

Typeahead/Bloodhound Remote not returning data

本文关键字:返回 数据 Remote Bloodhound Typeahead      更新时间:2023-09-26

我正在尝试使用typeahead(v0.10.5)/bloodhound来绑定返回的JSON数据。不幸的是,我的建议窗口(即<input >)中没有显示任何内容。此外,我使用的是jQuery v2.0.3。

对我的终结点的调用成功。当我在Chrome中检查结果时,我会看到一个格式正确的响应(即数据和内容类型)。Chrome的控制台窗口中没有出现任何错误。下面是JSON的一个示例。

我已插入调试器语句,但它们没有被命中。

jqXHR.setRequestHeader()在那里是因为我正在进行一些跨站点调用。

Html代码

<div id="remote">
    <input class="typeahead" type="text" placeholder="Prescription names">
</div>

Javascript代码

我离开了//调试器;语句来显示我试图添加断点的位置

<script type="text/javascript">
    $(document).ready(function () {
        var prescriptions = new Bloodhound({
            datumTokenizer: function (d) { return Bloodhound.tokenizers.whitespace(d.value); },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: '/Prescription/GetPrescriptions/?searchTerm=%QUERY',
                filter: function (prescriptions) {
                    //debugger;
                    return $.map(prescriptions, function (user) {
                        //debugger;
                        return {
                            value: user.Name 
                        };
                    });
                },
                ajax: {
                    type: 'GET',
                    dataType: 'jsonp',
                    beforeSend: function (jqXHR, settings) {
                        var authHeaders;
                        // pull apart jqXHR, set authHeaders to what it should be
                        //debugger;
                        jqXHR.setRequestHeader('Access-Control-Allow-Origin', '*');
                    }
                }
            }
        });
        // initialize the bloodhound suggestion engine
        prescriptions.initialize();
        // instantiate the typeahead UI
        $('#remote .typeahead').typeahead({
            minLength: 3,
            highlight: true,
            hint: true
        },
            {
                name: 'prescriptions',
                displayKey: 'value',
                source: prescriptions.ttAdapter()
            });
    });
</script>

JSON结果

[{"Name":"Drug1"}]

任何想法都将不胜感激。

Steve

我的代码出现的问题原来是dataType: "jsonp"语句。我对代码进行了多次迭代。有一次,我引用了一个不同的领域。这导致我使用jsonp数据类型。

最后,我引用了一个不需要jsonp数据类型的相对Url。

我将ajax调用更改为dataType: "json",并修复了它。