我在 json 对象中从 Yahoo Finance 提取股票符号,并尝试在用户开始在搜索框中输入公司名称或符号时将它们显示为下拉菜单。
Typeahead 不能用作搜索框中的下拉菜单。这是我到目前为止的代码。
例如,如果我在将 {$_POST['symbol']} 替换为 goog 的同时将 $data 或 $result 转储到Suggest.php 中,我将得到一个数组。所以,我在想,要么Suggest.php echo 没有返回任何东西,要么没有从quote.js 文件中调用suggest.php。
如果我删除了建议.php 中的 if 语句并用 goog 替换 {$_POST['symbol']} 然后转到不http://localhost/suggest.php
应该回显打印什么东西?
任何帮助表示赞赏。我是网络开发的新手,正在努力学习。
引用.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;
});
});
报价单.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"]);
}
?>
报价搜索.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>
建议.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']}®ion=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]));
}
?>