Ajax typeahead不起作用

时间:2013-04-02 17:02:24

标签: php jquery ajax twitter-bootstrap web-deployment

我在json对象中从Yahoo finance中提取股票代码,我试图在用户开始在搜索框中输入公司名称或符号时将其显示为下拉菜单。

预先输入不是搜索框中的下拉菜单。这是我到目前为止的代码。

如果我在使用goog替换{$ _POST ['symbol']}时将$ data或$ result转储到suggest.php中,我将获得一个数组。所以,我认为suggest.php echo没有返回任何内容或者quote.php没有从quote.js文件中调用。

如果我删除了suggest.php中的if语句并用goog替换{$ _POST ['symbol']}然后转到http://localhost/suggest.php不应该回显一些东西?

感谢任何帮助。我是网络开发的新手并且正在努力学习。

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 = array();
    $json = json_decode(substr($data, strlen('YAHOO.util.ScriptNodeDataSource.callbacks('), -1));
    foreach ($json->ResultSet->Result as $stock)
        $result[] = $stock;

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

?>

1 个答案:

答案 0 :(得分:4)

我看到一些错别字。如果这是测试服务器,您可能希望在php中启用错误。

无论如何,从这段代码:

// load suggestion data
$data = @file_get_contents("http://d.yimg.com/aq/autoc?query=GOOG&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks");

// parse yahoo data into a list of symbols
$patt = array("/^YAHOO\.util\.ScriptNodeDataSource\.callbacks\(/","/\)$/");
$repl = array("","");
$json = json_decode(preg_replace($patt,$repl,$data));

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

echo json_encode(array('symbols' => $result));

我得到以下输出:

{"symbols":[{"symbol":"GOOG","name":"Google Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"^UVSPY","name":"NASDAQ OMX Alpha GOOG vs. SPY","exch":"NAS","type":"I","exchDisp":"NASDAQ","typeDisp":"Index"},{"symbol":"GOOG-U.TI","name":"GOOGLE-A","exch":"TLO","type":"S","exchDisp":"TLX Exchange ","typeDisp":"Equity"},{"symbol":"GOOG11BF.SA","name":"GOOGLE -DRN MB","exch":"SAO","type":"S","exchDisp":"Sao Paolo","typeDisp":"Equity"},{"symbol":"GOOG.MX","name":"Google Inc.","exch":"MEX","type":"S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GOOF.EX","name":"GOOGLE-A","exch":"EUX","type":"S","exchDisp":"EUREX Futures and Options Exchange ","typeDisp":"Equity"},{"symbol":"GGQ1.F","name":"GOOGLE-A","exch":"FRA","type":"S","exchDisp":"Frankfurt","typeDisp":"Equity"},{"symbol":"GGQ1.MU","name":"GOOGLE-A","exch":"MUN","type":"S","exchDisp":"Munich","typeDisp":"Equity"},{"symbol":"GGQ1.HA","name":"GOOGLE-A","exch":"HAN","type":"S","exchDisp":"Hanover","typeDisp":"Equity"},{"symbol":"GGQ1.DE","name":"GOOGLE-A","exch":"GER","type":"S","exchDisp":"XETRA","typeDisp":"Equity"}]}

如果您正在使用Bootstrap 2.1+更正数据获取和解析,您应该能够按照this answer中的描述实现对PHP代理的ajax调用。 (如果链接没有跳到它,请搜索“Bootstrap 2.1”页面。)