ajax的封装--简单实现根据学号查询学生信息(包含调用jQuery的ajax包基本用法)

    科技2022-07-10  123

    ajax.js文件

    function ajax (type,url,param,dataType,callback) { // body... var xhr = window.XMLHttpRequest ? new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); if (type == 'get') { url += "?"+encodeURI(param); } xhr.open(type,url,true); var data =null; if (type == 'post') { data = param; xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xhr.send(data); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){ var res = xhr.responseText; if (dataType == 'json') { res =JSON.parse(res); } console.log(res); callback(res); } } } }

    后台数据设置-假数据

    <?php $id = $_GET["id"]; $arr = array(); $arr[110] = array("name"=>"李红","age"=>21,"sex"=>"女","grade"=>"2021"); $arr[112] = array("name"=>"张彩","age"=>22,"sex"=>"女","grade"=>"2018"); $arr[113] = array("name"=>"李四","age"=>22,"sex"=>"女","grade"=>"2020"); $arr[114] = array("name"=>"吴武","age"=>20,"sex"=>"男","grade"=>"2021"); //首先判断学号是否存在,array_key_exists:判断数组中有无对应的键,有返回1 if (array_key_exists($id,$arr) == 1) { $arr = json_encode($arr[$id]); echo $arr; }else{ echo '{"flag":0}'; } ?>

    前端获取

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax封装</title> <style type="text/css"> .box{ width: 400px; min-height: 200px; background-color: skyblue; margin: auto auto; line-height: 26px; text-align: center; color: #fff; } #show{ margin-top: 10px; /*background-color: orange;*/ } </style> //------JQuery可替换区域 <script type="text/javascript" src="ajax.js"></script> <script type="text/javascript"> //功能:根据学号查询学生信息 window.onload =function(){ document.getElementById("btn").onclick =function(){ var id = document.getElementById('id').value; ajax('get','index3.php','id='+id,'json',function(data){ var show = document.getElementById("show"); if (data.flag == 0) { show.innerHTML = '没有这个学生!'; show.style.color = 'red'; }else{ var str = '姓名:'+data.name+' 年龄:'+data.age+' 性别:'+data.sex+' 年级:'+data.grade; show.innerHTML = str; show.style.color = 'white'; } }) } } </script> //------- </head> <body> <div class="box"> 学号:<input type="text" name="id" id="id"> <button id="btn">查询</button> <div id="show"></div> </div> </body> </html>

    结果: 查无此人 查询成功 jQuery写法,前提要导入jQuery.js文件

    <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> //功能:根据学号查询学生信息 $(function(){ $("#btn").click(function(){ var id = $('#id').val(); $.ajax({ type:'get', url:'index3.php',//更加方便 data:{id:id}, // url:'index3.php?id='+id, dataType:'json',//要指定,否则默认text success:function(data){ if (data.flag == 0) { $("#show").html('没有这个学生!'); $("#show").css({"color":"red"}); }else{ var str = '姓名:'+data.name+' 年龄:'+data.age+' 性别:'+data.sex+' 年级:'+data.grade; $("#show").html(str); $("#show").css({"color":"#fff"}); } }, error:function(data){ // } }) }); }); </script>
    Processed: 0.019, SQL: 8