PHP 初心者向け AJAX 投票入門
AJAX投票
次の例では、Webページを更新せずに投票結(jié)果が表示される投票プログラムを示します
まず、次のようなコードのphpファイルを作成します:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script> function getVote(int) { if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 執(zhí)行代碼 xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 執(zhí)行代碼 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("poll").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","demo.php?vote="+int,true); xmlhttp.send(); } </script> </head> <body> <div id="poll"> <h3>你喜歡 PHP 和 AJAX 嗎?</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>
コードの説明:
getVote() 関數(shù)は次の手順を?qū)g行します:
XMLHttpRequest オブジェクトを作成する
サーバー応答の準(zhǔn)備ができたときに実行される関數(shù)を作成する
サーバー上のファイルにリクエストを送信する
URL の最後にパラメーター (q) を追加することに注意してください (ドロップダウン リストの內(nèi)容が含まれます)
次に、demo.php ファイルを作成します。 コードは次のとおりです。
<?php $vote = htmlspecialchars($_REQUEST['vote']); // 獲取文件中存儲的數(shù)據(jù) $filename = "poll_result.txt"; $content = file($filename); // 將數(shù)據(jù)分割到數(shù)組中 $array = explode("||", $content[0]); $yes = $array[0]; $no = $array[1]; if ($vote == 0){ $yes = $yes + 1; } if ($vote == 1){ $no = $no + 1; } // 插入投票數(shù)據(jù) $insertvote = $yes."||".$no; $fp = fopen($filename,"w"); fputs($fp,$insertvote); fclose($fp); ?> <h2>結(jié)果:</h2> <table> <tr> <td>是:</td> <td> <span style="display: inline-block; background-color:green; width:<?php echo(100*round($yes/($no+$yes),2)); ?>px; height:20px;" ></span> <?php echo(100*round($yes/($no+$yes),2)); ?>% </td> </tr> <tr> <td>否:</td> <td> <span style="display: inline-block; background-color:red; width:<?php echo(100*round($no/($no+$yes),2)); ?>px; height:20px;"></span> <?php echo(100*round($no/($no+$yes),2)); ?>% </td> </tr> </table>
コードの説明:
When選択した値が JavaScript から PHP ファイルに送信され、何が起こります:
1. "poll_result.txt" ファイルの內(nèi)容を取得します
2. ファイルの內(nèi)容を変數(shù)に入れ、選択した変數(shù)に 1 を追加します
3. 結(jié)果を「poll_result.txt」ファイルに書き込みます
4. 投票結(jié)果をグラフィカルに出力します