0

我正在尝试提前输入 (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"}]

任何想法将不胜感激。

史蒂夫

4

1 回答 1

0

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

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

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

于 2014-10-10T17:18:54.850 回答