一个小功能,临时用的时候写起来麻烦,所以整理一下,就是普通的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;
}
?>
最终效果: