PHP+AJAX 投票器功能
終于到AJAX,翻譯過來就是”異步Javascript和XML”,他可以實現(xiàn)網頁內容的部分加載,可提高用戶體驗?,F(xiàn)在有很多網站都有用這技術,反正你知道他能實現(xiàn)網頁的異步更新就差不多了。當然下面的例子都相對簡單,并沒有體現(xiàn)它這一特點~
投票器
新建文件【 AJAX投票.html】
<html>
<head>
<script type="text/javascript">
// 這里是js代碼
function getVote(int) {
if (window.XMLHttpRequest) {
// 創(chuàng)建 XMLHttpRequest 對象
// IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行的代碼
xmlhttp = new XMLHttpRequest();
} else {
//IE6, IE5 瀏覽器執(zhí)行的代碼
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 監(jiān)聽響應
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState ==4 && xmlhttp.status == 200) {
// 找到 id 為 poll 的控件
document.getElementById('poll').innerHTML = xmlhttp.responseText;
}
}
// 向PHP腳本傳遞主要參數(shù)q
xmlhttp.open("GET", "poll_vote.php?q=" + int, true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="poll">
<h3>你喜歡吃嗎?</h3>
<form>
是:<input type="radio" name="vote" value="0" onclick="getVote(this.value)"><br>
否:<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
創(chuàng)建【poll_vote.php】腳本文件
<?php
// 接收參數(shù)q
$vote = htmlspecialchars($_REQUEST['q']);
// 獲取文件中存儲的數(shù)據(jù)(這里需要在同一目錄下新建一個poll_result.txt文件)
$filename = "poll_result.txt";
$conn = file($filename);
// 將數(shù)據(jù)分割到數(shù)組
$array = explode("||", $conn[0]);
$yes = $array[0];
$no = $array[1];
$count = $array[2];
if ($vote == 0) {
$yes += 1;
$count += 1;
}
if ($vote == 1) {
$no += 1;
$count += 1;
}
// 將投票數(shù)據(jù)保存到文檔
$insertvote = $yes . '||' . $no . '||' . $count;
$fp = fopen($filename, "w");
fputs($fp, $insertvote);
fclose($fp);
?>
<h2>結果:</h2>
<table>
<tr>
<td>是:</td>
<td>
<span style="display: inline-block; background-color: green; width: <?php echo 100 * round($yes / ($yes + $no), 2);?>px; height: 20px;"></span><?php echo 100 * round($yes / ($yes + $no), 2); ?>%
</td>
</tr>
<tr>
<td>否:</td>
<td>
<span style="display: inline-block; background-color: red; width: <?php echo 100 * round($no / ($yes + $no), 2);?>px; height: 20px;"></span><?php echo 100 * round($no / ($yes + $no), 2); ?>%
</td>
</tr>
</table>
<p><?php echo "參與人數(shù):" . $count; ?></p>
新建一個空白的文檔 【poll_result.txt】
此時目錄:
|-AJAX投票.html
|-poll_vote.php
|-poll_result.txt
如果不同則需修改上面相應的代碼
效果:

總結
以上所述是小編給大家介紹的PHP+AJAX 投票器功能,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
相關文章
ThinkPHP5.0框架使用build 自動生成模塊操作示例
這篇文章主要介紹了ThinkPHP5.0框架使用build 自動生成模塊操作,結合實例形式分析了thinkPHP5使用build自動生成模塊的具體步驟、方法與相關操作注意事項,需要的朋友可以參考下2019-04-04
php打亂數(shù)組二維數(shù)組多維數(shù)組的簡單實例
下面小編就為大家?guī)硪黄猵hp打亂數(shù)組二維數(shù)組多維數(shù)組的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06

