我拉從json對象的雅虎財務股票的符號,我試圖顯示他們作爲一個下拉菜單,而用戶開始在搜索框中鍵入公司名稱或符號。阿賈克斯typehead不能正常工作
Typeahead不作爲搜索框中的下拉菜單工作。這是迄今爲止的代碼。
如果我用$ go替換{$ _POST ['symbol']}來轉儲$ data或$ result在suggest.php中,例如我得到一個數組。所以,我在想,要麼建議。PHP回聲沒有返回任何東西或建議。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']}®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]));
}
?>
感謝您的回覆。我的確得到了和你一樣的結果。有沒有辦法檢查ajax函數是否正常工作?我仍然無法獲得下拉菜單。 – tironci
更新?你說我修正了PHP輸出,但你沒有接受我的答案。您是否按照我鏈接的答案更新了您的ajax電話? –
我得到了您的更改結果,但是當我嘗試從ajax獲得結果時,我仍然無法獲得下拉菜單。 – tironci