一个小功能,临时用的时候写起来麻烦,所以整理一下,就是普通的ajax请求获取反馈,只是框架用久了,有点生疏.
查看手册地址:
http://www.w3school.com.cn/jquery/ajax_ajax.asp
数据库 acorse.sql
PRIMARY KEY (`id`)CREATE TABLE `acorse` ( `id` int UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT COMMENT 'ID',`rank` char(4) NOT NULL COMMENT '等级',`min_score` int NOT NULL COMMENT '最小积分',`max_score` int NOT NULL COMMENT '最大积分',) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `acorse` (`id`,`rank`,`min_score`,`max_score`) VALUES (1,'L1',1,50),(2,'L2',51,100),(3,'L3',101,150);
前端页面(需要引入jquery-3.2.1.min.js自行下载)score.html
<!DOCTYPE html> <html> <head> <Meta charset="utf-8"> <title>等级查询</title> <script type="text/javascript" src='jquery-3.2.1.min.js'></script> </head> <body> <form method="get"> <p>输入成绩: <input type="text" name="score" /> 等级: <span id='result'></span></p> </form> <button id="send">提交</button> </body> <script type="text/javascript"> $(function(){ $("#send").click(function(){ var cont = $("input").serialize(); $.ajax({ url:'ajax.PHP',type:'get',dataType:'json',data:cont,success:function(data){ //console.log(data) var str = data; $("#result").html(str); } }); }); }); </script> </html>
后台PHP接收,查询数据库(由于没有框架,所以使用MysqLi类,如果有框架则可以简化) ajax.PHP
<?PHP header("Content-type:text/html;charset=utf-8"); $MysqLi = new MysqLi('localhost','用户名','密码','数据库名'); /* * This is the "official" OO way to do it,* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0. */ if ($MysqLi->connect_error) { die('Connect Error (' . $MysqLi->connect_errno . ') ' . $MysqLi->connect_error); } $MysqLi->set_charset('utf8'); $sql = 'select * from acorse'; $res = getAll($sql,$MysqLi); $MysqLi->close(); // var_dump($res); $lv = ''; $score = isset($_GET['score'])?$_GET['score']:''; $min = $max = 0; $min = reset($res)['min_score']; $max = end($res)['max_score']; if ($score>=$min && $score<=$max) { foreach ($res as $k => $v) { if ($score>$v['min_score'] && $score<$v['max_score']) { $lv = $res[$k]['rank']; break; } } } echo json_encode($lv); function getAll($sql,$MysqLi){ if($res = $MysqLi->query($sql)){ //定义一空数组,用来装我们的记录 $arr = array(); while($row = $res->fetch_assoc()){ $arr[] = $row; } }else{ echo '<br> sql执行失败,原因是'; die('info:' . $MysqLi->error); } //可以马上是否结果集 $res->free(); return $arr; } ?>
最终效果: