简体   繁体   English

Bootstrap Typeahead不适用于从PHP页面检索的动态数组

[英]Bootstrap typeahead not working with dynamic array retrieved from a php page

I was trying to create a autocomplete box that gets stock symbols and names from finance.yahoo.com according to the user query typed in typeahead text box. 我正在尝试创建一个自动完成框,该框根据键入在预输入文本框中的用户查询从finance.yahoo.com获取股票代码和名称。

I created a quote_form.php page in which there is a text box on which i applied jquery keyup function to get the characters when typed by the user and then based on that characters i made a get request inside my typeahead function on my php page called symbols.php which inturn calls this link below: 我创建了一个quote_form.php页面,其中有一个文本框,在该文本框上我应用了jquery keyup函数来获取用户键入的字符,然后基于这些字符,我在php页面上的typeahead函数内发出了一个get请求。 Symbols.php依次在下面调用此链接:

http://d.yimg.com/aq/autoc?query= $search&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks http://d.yimg.com/aq/autoc?query= $ search&region = US&lang = zh-CN&callback = YAHOO.util.ScriptNodeDataSource.callbacks

In the above link $search contains the characters received by get request and then in response i received JSON data with some junk i cleared the junk and then made it a legitimate JSON data and from that JSON data i created a string that looks like javascript array with the field i needed from the JSON. 在上面的链接中,$ search包含由get请求接收的字符,然后作为响应,我收到了带有垃圾的JSON数据,我清除了垃圾,然后将其制成合法的JSON数据,并从该JSON数据中创建了一个类似于javascript数组的字符串与我需要从JSON的字段。 So, when my quote_form.php receives that data it does not shows it in typeahead. 因此,当我quote_form.php接收到该数据时,不会提前输入。 I surely receive data as i have seen in chrome's inspect element's Network tab. 我肯定会收到我在chrome的inspect元素的“网络”标签中看到的数据。 The code for both the pages is as below, i have created a seperate html header so i will not include the same as it is not necessary: 这两个页面的代码如下,我创建了一个单独的html标头,因此我将不包含它,因为这是没有必要的:

I have included the necessary javaScript files and CSS files: 我已经包含了必要的javaScript文件和CSS文件:

jquery version used: 1.8.2 使用的jquery版本:1.8.2

Bootstrap version used: v2.2.1 使用的引导程序版本:v2.2.1

quote_form.php quote_form.php

    <script type ="text/javascript">
    $(document).ready(function () {
    var key;
    $("input[name='symbol']").keyup(function() {
        console.log("Key pressed");
        window.key = $(this).val();
    });

    $("input[name='symbol']").typeahead({
        source: function(query, process) {
        return $.get('symbols.php', {s: window.key}, function(data) {
            console.log(data);
            return process(data);
            });
        }
    });

});

</script>

<form action="quote.php" method="post">
    <fieldset>
        <div class="control-group">
            <input id = "sy" autofocus autocomplete ="off" name="symbol" placeholder="Symbol" type="text"/>
        </div>
        <div class="control-group">
            <button type="submit" class="btn">Get Quote</button>
        </div>
    </fieldset>
</form>

symbols.php symbols.php

<?php
    $search = $_GET['s'];

    $url = "http://d.yimg.com/aq/autoc?query=$search&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks";

    $raw_data =  @file_get_contents($url);

    $json = substr($raw_data, strpos($raw_data,'Result"') - 1);
    $json = rtrim($json, '})');
    $json = "{" . $json . "}";

    $result = json_decode($json, true);

    $jsarr = "[";
    foreach($result as $symbols)
    {
    foreach($symbols as $symbol)
    {
        $jsarr .= "'".$symbol['name'] . " " . $symbol['symbol'] . "', ";
    }
    }

    $jsarr .= "]";

    echo $jsarr;
?>

I also tried the above code without converting to JavaScript array ie i also tried with JSON only but that didn't work either. 我也尝试了上面的代码而未转换为JavaScript数组,即我也仅尝试了JSON,但这也不起作用。 Seen many examples on internet also but still i am missing something don't know what. 在互联网上也看到了很多例子,但我仍然错过了一些不知道的东西。 If any body can figure out what i am doing wrong that would be a great relief for me. 如果有人能弄清我做错了什么,那对我来说将是极大的缓解。

Thanks in advance. 提前致谢。

The Yahoo API is actually returning a JSONP callback, you can avoid the parsing by making a jsonp request directly from jquery, you just need to build the YAHOO object that's specified in the callback: Yahoo API实际上返回了JSONP回调,您可以通过直接从jquery发出jsonp请求来避免解析,您只需要构建在回调中指定的YAHOO对象即可:

var $typeaheadInput = $("input[name='symbol']");
$typeaheadInput.typeahead({
    source: function (query, process) {
        return $.ajax({
            url: 'http://d.yimg.com/aq/autoc?query=' + query + '&region=US&lang=en-US',
            dataType: 'jsonp',
            jsonpCallback: 'YAHOO.util.ScriptNodeDataSource.callbacks'
        });
    }
});

//Build YAHOO object with callback function
YAHOO = {
    util: {
        ScriptNodeDataSource: {
            callbacks: function (data) {
                var sourceArray = $.map(data.ResultSet.Result, function (elem) {
                    return elem.name + ' - ' + elem.symbol;
                });
                $typeaheadInput.data('typeahead').process(sourceArray);
            }
        }
    }
};

Here's a working fiddle 这是一个工作的小提琴

Note: I removed the autofocus attribute from the input because it was causing issues with the typeahead dropdown 注意:我从输入中删除了autofocus属性,因为它引起了typeahead下拉列表的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM