【发布时间】:2015-06-25 06:49:17
【问题描述】:
我使用 jQuery AJAX 和 JSON 创建了简单的东西。我想知道如何创建一个会话,以便用户无法再次投票。以下是我的代码。
我是 Sessions 和 jQuery 的新手。请告诉我如何完成我的任务。
JavaScript
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV=
{
"vote": count
};
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function (responseText){
console.log("Shit is working "+responseText);
$("#result").html(responseText.vote);
},
complete : function(){
$("#poll").slideUp();
},
error : function(error,responseText){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log(error);
$("#result").html(error+ responseText);
alert(count);
}
});
});
});
</script>
PHP
<?php
$vote = $_REQUEST['vote'];
$filename = "poll_result.txt";
$content = file($filename);
// $decode = json_decode($encode);
$array = explode("||", $content[0]);
$male = $array[0];
$female = $array[1];
if ($vote == 0) {
$male = $male + 1;
}
if ($vote == 1) {
$female = $female + 1;
}
$insertvote = $male."||".$female;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
$table = (
"<h2>Results:</h2>
<table>
<tr>
<td> Male :</td>
<td>
<img src='poll.gif'
width= ".(100*round($male/($female+$male),2)).
"height='20'>".
(100*round($male/($female+$male),2))." %" .
"
</td>
</tr>
<tr>
<td> Female :</td>
<td>
<img src='poll.gif'
width=". (100*round($female/($female+$male),2)) .
"
height='20'>".
(100*round($female/($female+$male),2))." %" ."
</td>
</tr>
</table>");
$list = array('vote' => $table);
$encode = json_encode($list);
echo $encode;
?>
HTML
<div id= "poll">
<h3> What is your Gender? </h3>
<form>
Male :
<input type = "radio" name = "vote" id="vote1" >
<br>
Female :
<input type = "radio" name = "vote" id="vote2" >
</form>
</div>
<p><div id= "result"></div>
</body>
【问题讨论】:
-
我猜 Cookie 会是更好的选择。
-
使用
session_start()function.and set session variables.as$_SESSION["login"] = "green"; -
@LShetty 你能告诉我怎么做吗?
标签: javascript php jquery session vote