Bootstrap typeahead不起作用

时间:2013-04-01 12:49:29

标签: php jquery twitter-bootstrap jquery-autocomplete

我在json对象中从Yahoo finance中提取股票代码,我试图在用户开始在搜索框中输入公司名称或符号时将其显示为下拉菜单。 Typeahead不能作为搜索框中的下拉菜单。我想我做的一切都是正确的。这是我到目前为止的代码。任何帮助表示赞赏。

quote.js

$(document).ready(function() {

  // create autocomplete
  $('#form-quote input[name=symbol]').typeahead({

      // load autocomplete data from suggest.php
      source: function(query, callback) {
          $.ajax({
              url: '../suggest.php',
              type: 'POST',
              dataType: 'json',
              data: {
                  symbol: query
              },
              success: function(response) {
                  callback(response.symbols);

              }
          });
      }
  });

  // load data via ajax when form is submitted
  $('#form-quote').on('click', function() {

      // determine symbol
      var symbol = $('#form-quote input[name=symbol]').val();

      // send request to quote.php
      $.ajax({
          url: 'quote.php',
          type: 'POST',
          data: {
              symbol: symbol
          },
          success: function(response) {
              $('#price').text(response);
          }
      });


      return false;
  });

});

quote.php

<?php

//configuration
require("../includes/config.php");

//if form was submitted 

if($_SERVER["REQUEST_METHOD"] == "POST"){

    $stock = lookup(strtoupper($_POST["symbol"]));

    if(empty($_POST["symbol"])){

        //echo "You must enter a stock symbol";

    }else if($_POST["symbol"]){

    $price = number_format($stock['price'], 2);

    echo "A share of {$stock['name']} costs $$price";
    }
}

else{

    // render portfolio
render("stock_search.php", ["title" => "Get Quote"]);
}   
?>

quote_search.php

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

    <div class="control-group">
        <button type="submit" class="btn">Get Quote</button>
    </div>

</fieldset>
<div id="price"></div>
<div id="suggestions"></div> 
</form>
<script type="text/javascript" src="js/quote.js" ></script>

suggest.php

 <?php

// configuration
require("../includes/functions.php");

// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    // load suggestion data
$data = @file_get_contents("http://d.yimg.com/aq/autoc?query=  {$_POST['symbol']}&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks");

    // parse yahoo data into a list of symbols
$result = [];
    $json = json_decode(substr($data, strlen('YAHOO.util.ScriptNodeDataSource.callbacks('), -1));
    foreach ($json->ResultSet->Result as $stock)
        $result[] = $stock;

    echo json_encode(['symbols' => $result]);
}

?>

4 个答案:

答案 0 :(得分:1)

Typeahead只接受一个字符串数组作为源

  // i.e.
  ["INTC", "GOOG", "FB", /* etc */]

您的脚本所做的是创建Yahoo返回的整个对象的数组

  // i.e.
  [
    {"symbol":"INTC","name": "Intel Corporation","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},
    {"symbol":"INTC.MX","name": "Intel Corporation","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},
    /* etc */
  ]

您需要做的是更改您的suggest.php以便行:

foreach ($json->ResultSet->Result as $stock)
        $result[] = $stock;

成为例子:

foreach ($json->ResultSet->Result as $stock)
        $result[] = '('.$stock->symbol.') '.$stock->name;

答案 1 :(得分:0)

尝试在Ajax中添加您的网址的完整路径,例如localhost/app/user/suggest.php

答案 2 :(得分:0)

确保在使用json_encode回复之前将“Content-type”设置为json。

header("Content-type: application/json");

答案 3 :(得分:0)

愚蠢的问题,但是你期待的json结果,即使将比赛退出等式,这还能正确回归吗?因为传递给file_get_contents的值可能会有点拙劣,除非在这里粘贴时格式被轰炸。