我正在尝试通过创建股票投资组合来学习 php 和 javascript。我想要做的是自动更新表格的价格单元格,而无需使用 javascript 刷新页面。我创建了一个新的 php 文件,仅将那个价格字段添加到投资组合中,但我似乎无法让它工作。我在那个价格字段上有很多错误。我已将所有文件都放在这里pastebin。任何帮助,将不胜感激。
portfolio.php file
<table class="table table-hover center-table table-bordered">
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Shares</th>
<th>Price</th>
<th>Total</th>
</tr>
<?php foreach ($shares as $row): ?>
<tr>
<td><?= $row["symbol"]?></td>
<td><?= $row["name"]?></td>
<td><?= $row["shares"]?></td>
<td id="price">$<?= number_format($row["price"],2)?></td>
<td>$<?= number_format($row["total"],2)?></td>
</tr>
<? endforeach ?>
<tr>
<td>CASH</td>
<td></td>
<td></td>
<td></td>
<td>$<?= number_format($cash[0]["cash"], 2)?></td>
</tr>
</table>
<script type="text/javascript" src="js/update.js" ></script>
index.php 文件
<?php
// configuration
require("../includes/config.php");
//query user's portfolio
$rows = query("SELECT * FROM shares WHERE id = ?", $_SESSION["id"]);
$cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//create array to store the shares
$shares = [];
//for each of the user info
foreach($rows as $row){
//lookup stock info
$stock = lookup($row["symbol"]);
if($stock !== false){
$shares[] = [
"name" => $stock["name"],
"price" => $stock["price"],
"shares" => $row["shares"],
"symbol" => $row["symbol"],
"total" => $row["shares"]*$stock["price"]
];
//dump($shares);
}
}
// render portfolio
render("portfolio.php", ["shares" => $shares,"cash" => $cash, "title" => "Portfolio"] );
?>
更新.php
<?php
require("../includes/functions.php");
require("../includes/config_update.php");
$rows = query("SELECT * FROM shares WHERE id = ?", $_SESSION["id"]);
$cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//create array to store the shares
$shares = [];
//for each of the user info
foreach($rows as $row){
$stock = lookup($row["symbol"]);
if($stock !== false){
$shares[] = [
"name" => $stock["name"],
"price" => $stock["price"],
"shares" => $row["shares"],
"symbol" => $row["symbol"],
"total" => $row["shares"]*$stock["price"]
];
}
}
// render portfolio
render("portfolio.php", ['shares' => $shares, 'cash' => $cash]);
?>
更新.js
$(document).ready(function(){
var updater = setTimeout(function(){
$('#price').load('update.php', 'update=true');
},6);
});
当我第一次运行它时,我在价格单元格中得到了整个表格以及这些错误消息注意:未定义的变量:portfolio.php 中的股票第 10 行为第 10 行的portfolio.php 中的 foreach() 提供的参数无效未定义的变量兑现第 31 行的投资组合.php
我不再收到任何错误,但现在我在表格的价格字段中获得了整个页面。