Alex的博客

本博客的文章均为原创,是本人从事行业多年来所遇见一些小问题的解决心得,希望可以帮助到大家!



php+js实现简单抽奖

html:


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>演示:使用jQuery+PHP+Mysql实现抽奖程序</title>

<style type="text/css">
.demo{width:300px; margin:60px auto; text-align:center}
#roll{height:32px; line-height:32px; margin-bottom:10px; font-size:24px; color:#f30}
.btn{width:80px; height:26px; line-height:26px; background:url(btn_bg.gif) repeat-x; border:1px solid #d3d3d3; cursor:pointer}
#stop{display:none}
#result{margin-top:20px; line-height:24px; font-size:16px; text-align:center}
</style>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">

$(function(){
  var _gogo;
  var start_btn = $("#start");
  var stop_btn = $("#stop");

  start_btn.click(function(){
    $.getJSON('data.php',function(json){
      if(json){
        //var obj = eval(json);//通过eval() 函数可以将JSON字符串转化为对象
        var len = json.length;
        _gogo = setInterval(function(){
          var num = Math.floor(Math.random()*len);
          //var id = obj[num]['id'];
          var id = json[num].id;
          //var v = obj[num]['mobile'];
          var v = json[num].mobile;
          $("#roll").html(v);
          $("#mid").val(id);
        },100);
        stop_btn.show();
        start_btn.hide();
      }else{
        $("#roll").html('系统找不到数据源,请先导入数据。');
      }
    });
    //_gogo = setInterval(show_number,100);
  });

  stop_btn.click(function(){
    clearInterval(_gogo);
    var mid = $("#mid").val();
    $.post("data.php?action=ok",{id:mid},function(msg){
      if(msg==1){
        var mobile = $("#roll").html();
        $("#result").append("<p>"+mobile+"</p>");
      }
      stop_btn.hide();
      start_btn.show();
    });
  });

});


</script>
</head>

<body>


<div id="main">

  <div class="demo">
     <div id="roll"></div>
     <input type="hidden" id="mid" value="">
     <p><input type="button" class="btn" id="start" value="开始">
     <input type="button" class="btn" id="stop" value="停止"></p>
     <div id="result"></div>
  </div>
</div>
</body>
</html>


php部分[data.php]

include_once('connect.php'); //连接数据库

$action = $_GET['action'];
if($action==""){ //读取数据,返回json
    $query = mysql_query("select * from member where status=0");
        while($row=mysql_fetch_array($query)){
        $arr[] = array(
            'id' => $row['id'],
            'mobile' => substr($row['mobile'],0,3)."****".substr($row['mobile'],-4,4)
        );
    }
    echo json_encode($arr);
}else{ //标识中奖号码
    $id = $_POST['id'];
    $sql = "update member set status=1 where id=$id";
    $query = mysql_query($sql);
    if($query){
        echo '1';
    }
}


数据库部分:
CREATE TABLE `member` (
  `id` int(11) NOT NULL auto_increment,
  `mobile` varchar(20) NOT NULL,
  `status` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;


浏览699  评论0  Alex于 2017-3-15 15:50
发言