AJAX 투표
AJAX Voting
다음 예시에서는 웹 페이지를 새로 고치지 않고도 투표 결과를 표시하는 투표 프로그램을 보여드리겠습니다.
PHP와 AJAX를 좋아하시나요?
예제 설명 - HTML 페이지
사용자가 위 옵션 중 하나를 선택하면, "getVote()"라는 함수를 실행합니다. 이 함수는 "onclick" 이벤트에 의해 트리거됩니다.
poll.html 파일 코드는 다음과 같습니다.
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script> function getVote(int) { if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 执行代码 xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 执行代码 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("poll").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","poll_vote.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() 함수는 다음 단계를 수행합니다. :
XMLHttpRequest 객체 생성
서버 응답이 준비되면 실행되는 함수 생성
서버의 파일에 보고 요청 보내기
URL 끝에 추가된 매개변수(q)를 참고하세요(드롭다운 목록의 내용 포함)
PHP 파일
위에서 JavaScript를 통해 호출되는 서버 페이지는 "poll_vote.php"라는 이름의 PHP 파일입니다.
<?php $vote = htmlspecialchars($_REQUEST['vote']); // 获取文件中存储的数据 $filename = "poll_result.txt"; $content = file($filename); // 将数据分割到数组中 $array = explode("||", $content[0]); $yes = $array[0]; $no = $array[1]; if ($vote == 0) { $yes = $yes + 1; } if ($vote == 1) { $no = $no + 1; } // 插入投票数据 $insertvote = $yes."||".$no; $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/($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>
선택한 값이 JavaScript에서 PHP 파일로 전송되면 어떻게 되나요?
"poll_result. txt" 파일
변수에 파일 내용을 넣고 선택한 변수에 1을 더합니다
결과를 "poll_result.txt"에 씁니다. " 파일
그래프 출력 투표 프로그램의 데이터는 텍스트 파일(
poll_result.txt )에 저장됩니다.
저장되는 데이터는 다음과 같습니다.
3||4
첫 번째 숫자는 "예"에 대한 투표 수를 나타내고, 두 번째 숫자는 "아니요" 투표 수를 나타냅니다.참고:
웹 서버(PHP) 이외의 다른 사람이 액세스하도록 허용하지 마세요. 웹 서버에서만 이 텍스트 파일을 편집할 수 있도록 허용해야 합니다.
추천 관련 비디오 튜토리얼: "AJAX 튜토리얼" http://www.php.cn/course/list/25.html