首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

實作基於 Ajax 的投票調查程式

     編輯:PHP 相關知識

前端頁面

<html>
<head>
<title>投票</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<style>
.poll {font-size:10pt; display:block}
.pollresult {font-size:12pt; display:none}
</style>
<?php
include_once('server1.server.php'); // Xajax 伺服端
$xajax->printJavascript();
?>
</head>
<body>
<script>
function back() {
    document.getElementById('poll').style.display = 'block';
    document.getElementById('pollresult').style.display = 'none';
    document.getElementById('pollresult').innerHTML = '';
}
function onSubmit() {
    xajax_poll(xajax.getFormValues('pollForm'));
    document.getElementById('poll').style.display = 'none';
    document.getElementById('pollresult').style.display = 'block';
}
</script>

<div id="pollresult" class="pollresult"></div>

<?php
global $db;
$poll = $db->getRow('SELECT * FROM TBL_POLL ORDER BY poll_id DESC LIMIT 1');
$poll_id = $poll['poll_id'];
$pollitems = $db->getAll('SELECT * FROM TBL_POLLITEM WHERE poll_id=' . $poll_id);
?>

<div id="poll" class="poll">
<form id="pollForm" action="javascript:void(null);" onsubmit="onSubmit();">
<?php echo $poll['title']; ?><br>
<?php foreach ($pollitems as $item): ?>
<input type="radio" name="pollitem" value="<?php echo $item['pollitem_id']; ?>">
<?php echo $item['content']; ?><br>
<?php endforeach; ?>
<input type="hidden" name="poll_id" value="<?php echo $poll_id; ?>">
<input type="submit" value="投票">
</form>
</div>
</body>
</html>

伺服端處理

function poll($formData) {
    global $db;
    $objResponse = new xajaxResponse();

    $poll_id = $formData['poll_id'];
    $pollitem_id = $formData['pollitem'];

    if ($pollitem_id > 0 && $poll_id > 0) {
        $db->query('UPDATE ' . TBL_POLLITEM . ' SET count=count+1 WHERE pollitem_id=' . $pollitem_id);
    }

    $poll = $db->getRow('SELECT * FROM TBL_POLL WHERE poll_id=' . $poll_id);
    $pollitems = $db->getAll('SELECT * FROM TBL_POLLITEM WHERE poll_id=' . $poll_id);

    $tmp = '<div align="center">' . $poll['title'] . '</div><br>';
    foreach ($pollitems as $item) {
        $tmp .= '<div align="left">' . $item['content'] . ': ' . $item['count'] . '</div>';
    }

    $objResponse->assign('pollresult', 'innerHTML', $tmp);
    return $objResponse;
}

關鍵技術點

  • 使用 Xajax 庫簡化 Ajax 伺服端註冊與前端呼叫。
  • 前端表單提交攔截,透過 xajax.getFormValues() 序列化表單資料。
  • 伺服端更新計數後,重新查詢並組裝 HTML 片段回傳,前端直接 innerHTML 更新。
  • 投票狀態切換:隱藏表單、顯示結果區塊。

資料表結構建議

CREATE TABLE TBL_POLL (
    poll_id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL
);

CREATE TABLE TBL_POLLITEM (
    pollitem_id INT AUTO_INCREMENT PRIMARY KEY,
    poll_id INT NOT NULL,
    content VARCHAR(255) NOT NULL,
    count INT DEFAULT 0
);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved