前段时间,我有一个项目,我必须为新闻管理、添加、编辑、删除等做某种 CMS。正如 Satya 评论的那样,如果你想做得很好,方法就是使用 AJAX。
我所做的是一个循环,就像你的一样,为使用 PHP mysql_fetch_assoc 获取的每一行在表中添加一个 tr (是的,我知道,表......)。我知道您不想要 PHP 帮助,但我认为这会对您有所帮助。
$res=mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($res)) {
foreach ($row as $col => $val) {
if ($col != "column you dont display or isn't 'ID' column" && $col != "another column you dont display, and so on") {
if ($col == "ID") $id = $val;
//use this to echo values in table/tr/td/div/span or whatever you use to display values
if ($col == "gold") {
echo 'whatever you want to echo using the gold value';
}
if ($col == "name of last column you are displaying") {
echo 'whatever you display for that column';
echo '<input type="text" value="Introduce quantity">';
//If you are on HTML5 you could just use id="{$id}" as it will be easier
echo '<a href="#" class="buy" id="i_{$id}" value="Introduce quantity">';
}
}
}
这里最重要的事情之一是跟踪每个项目的 ID,这样您就可以在向服务器发送 POST 请求时将它们关联起来。
我建议你使用 jQuery,它很容易使用
<script type="text/javascript">
$(document).ready(function () {
$(".buy").click(function(e) {
e.preventDefault();
// You get the id attribute of the button clicked, which contains the
// item ID. Then you substr the string to get just the id number. Example:
// The id of the clicked element is "i_2254" you use substr to get just the
// 2254 and send it to the php that process the buy
// If you choose the HTML5 id form I said above in the PHP, then var id=$(this).attr("id")
var id = $(this).attr("id").substr(2);
$.ajax({
type: "POST",
url: "buy_item.php",
async:false,
data: "itemID="+id,
success: function(data) {
// Here is where the magic occurs, this is what happens when you
// get the response, here is where you update the
// inventory, quantity, etc WITHOUT reloading.
// The variable data is the response of the server
// you just echo what you need on buy_item.php, and
// that will be data here
// A simple example is to change the value of an input
// with id="gold", you echo gold on php and...
$('#gold').val(data);
}
});
});
});
});
</script>
在 buy_item.php 中,您可以更新表的黄金值,并将项目添加到项目表中。使用 $_SESSION 变量存储用户会话名称并更新该用户的金币和物品。
我建议你调查一下 AJAX 和 jQuery(可选),它会有很大帮助!
我想基本上这会解决你的问题,我希望能收到游戏邀请:P