初识 ajax 前后端数据交互技术

原生Ajax

  • 实现Ajax的步骤

    • 创建XMLHttpRequest对象
    • 注册监听
    • 建立连接
    • 发送请求
  • 实现Ajax的六步走

    • 创建XMLHttpRequest对象
    • 建立连接
    • 发送请求
    • 注册监听 - onreadystatechange事件
    • 获取服务器端的通信状态 - readyState
    • 获取服务器端的状态码
  • 创建XMLHttpRequest对象

    function getXhr(){
      // 声明XMLHttpRequest对象
      var xhr = null;
      // 根据浏览器的不同情况进行创建
      if(window.XMLHttpRequest){
         // 表示除IE外的其他浏览器
	 xhr = new XMLHttpRequest();
      }else{
         // 表示IE浏览器
	 xhr = new ActiveXObject('Microsoft.XMLHttp');
      }
      return xhr;
   }
  • Ajax的核心对象 - 属性

    • readyState属性 表示当前服务器端的通信状态
      • 0: (服务器端)尚未初始化
      • 1: (服务器端)正在接收
      • 2: (服务器端)接收完毕
      • 3: (服务器端)正在响应
      • 4: (服务器端)响应完毕
    • status属性 表示当前服务器端的状态码
      • 200 - 请求成功
      • 404 - 网页找不到(请求路径不正确)
      • 500 - 服务器端错误
  • Ajax的核心对象 - 方法

    • open(method,url)方法
      • 作用: 与服务器端建立连接
      • 参数
        • method 设置请求类型(GET或POST)
        • url 设置请求地址
    • send()方法
      • 作用: 向服务器端发送请求参数
      • GET方式
        • send()方法不起作用(不能使用send()方法发送请求数据)
        • send()方法不能被省略 - send(null)
        • 请求数据 - 增加在URL?key=value
      • POST方式
        • send()方法起作用
        • send()方法调用前,调用setRequestHeader()方法
        • xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  • Ajax的核心对象 - 事件

    • onreadystatechange事件
      • 作用: 监听服务器端的通信状态
  • 接收服务器端的响应

    • 使用onreadystatechange事件监听服务器端
    • 判断readyState属性值等于4(响应完毕)
    • 保证status属性值为200(表示请求成功)
    • 使用responseText属性接收服务器端的响应数据
  • Ajax案例

<select id="province">
    <option>请选择</option>
</select>
<select id="city">
    <option>请选择</option>
</select>
<script>
// a. 创建XMLHttpRequest对象
var xhr = getXhr();
window.onload = function(){
// b. 建立连接 - open("get","province.php");
    xhr.open("get","province.php");
// c. 发送请求 - send(null)
    xhr.send(null);
// d. 接收服务器端的数据
    xhr.onreadystatechange = function(){
        if(xhr.readyState==4 && xhr.status==200){
            var data = xhr.responseText;
            // 将字符串转换为数组
            var provinces = data.split(",");
            // 遍历数组
            for(var i=0;i<provinces.length;i++){
                var option = document.createElement("option");
                var text = document.createTextNode(provinces[i]);
                option.appendChild(text);
                var province = document.getElementById("province");
                province.appendChild(option);
            }
        }
    }
}
var province = document.getElementById("province");
province.onchange = function(){
    var city = document.getElementById("city");
    var opts = city.getElementsByTagName("option");
    for(var z= opts.length-1; z> 0; z--){
        city.removeChild(opts[z]);
    }
    if(province.value != "请选择"){
        xhr.open("post","cities.php");
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send("province="+province.value);
        xhr.onreadystatechange = function(){
            if(xhr.readyState==4 && xhr.status==200){
                var data = xhr.responseText;
                var cities = data.split(",");
                for(var i=0;i<cities.length;i++){
                    var option = document.createElement("option");
                    var text = document.createTextNode(cities[i]);
                    option.appendChild(text);
                    city.appendChild(option);
                }
            }
        }
    }
    
}
function getXhr(){
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject("Microsoft.XMLHttp");
    }
    return xhr;
}
</script>
// province.php
<?php
	echo '山东省,辽宁省,吉林省';
?>
<?php
// cities.php
	// 1. 接收客户端发送的省份信息
	$province = $_POST['province'];
	// 2. 判断当前的省份信息,提供不同的城市信息
	switch ($province){
		case '山东省':
			echo '青岛市,济南市,威海市,日照市,德州市';
			break;
		case '辽宁省':
			echo '沈阳市,大连市,铁岭市,丹东市,锦州市';
			break;
		case '吉林省':
			echo '长春市,松原市,吉林市,通化市,四平市';
			break;
	}
	// 服务器端响应的是字符串
?>

基于jQuery的AJAX

  • jQuery-ajax相关API基本使用
<style>
    table {
        width: 600px;
        border-collapse: collapse;
    }
    td {
        height: 40px;
        text-align: center;
        border: 1px solid #CCC;
    }
</style>
<table>
    <tr>
        <td>日期</td>
        <td>星期</td>
        <td>晚上最低温度</td>
        <td>白天最高温度</td>
        <td>风</td>
    </tr>
</table>
<script>
    // 急速数据API
    // https://www.jisuapi.com/
$(function(){
    $("input[type=button]").on("click",function(){
        var cityName=$("#cityName").val();
        $.ajax({
            url:"http://api.jisuapi.com/weather/query",
            type:"get",
            data:{
                appkey:"7ca5f245254f2b88",
                city:cityName
            },
            dataType:"jsonp",
            success:function(data){
                var weathers=data.result.daily;
                //console.log(weathers);
                //解析json 格式的数据,将json 格式的数组与页面上面的标签进行组装,然后放在页面上面.
                var tr="";
                for(var i=0;i<weathers.length;i++){
                    tr+="<tr>";
                    tr+="<td>"+weathers[i].date+"</td>";
                    tr+="<td>"+weathers[i].week+"</td>";
                    tr+="<td>"+weathers[i].night.templow+"</td>";
                    tr+="<td>"+weathers[i].day.temphigh+"</td>";
                    tr+="<td>"+weathers[i].day.winddirect+"</td>";
                    tr+="</tr>";
                }
                $("table").append(tr);
            }
        });
    });
});
</script>
<style type="text/css">
#container {
    width: 360px;
    min-height: 100px;
    background-color: lightgreen;
    position: absolute;
    left: 50%;
    top: 10px;
    margin-left: -180px;
}
</style>
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript">
$(function(){
    $("#btn").click(function(){
        var code = $("#code").val();
        $.ajax({
            type:'get',
            url:'./11.php',
            data:{code:code},
            dataType:'json',
            success:function(data){
                if(data.flag == 0){
                    $("#info").html("该图书不存在");
                }else{
                    var tag = '<ul><li>书名:' + data.bookname + '</li><li>作者:' + data.author + '</li><li>描述:' + data.desc + '</li></ul>';
                    $("#info").html(tag);
                }
            },
            error:function(data){
                console.dir(data);
                $("#info").html("服务器发生错误,请与管理员联系");
            }
        });
    });
});
</script>
<section id="container">
    <div>
        图书编码:
        <input type="text" name="code" id="code">
        <input type="button" value="查询" id="btn">
    </div>
    <div id="info"></div>
</section>
<style type="text/css">
#container {
    width: 360px;
    min-height: 100px;
    background-color: lightgreen;
    position: absolute;
    left: 50%;
    top: 10px;
    margin-left: -180px;
}
</style>
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript">
$(function(){
    $("#btn").click(function(){
        var code = $("#code").val();
        var data = $.ajax({
            type:'post',
            url:'./11.php',
            async:false,
            data:{code:code},
            dataType:'json'
        });
        data = data.responseJSON;
        if(data.flag == 0){
            $("#info").html("该图书不存在");
        }else{
            var tag = '<ul><li>书名:' + data.bookname + '</li><li>作者:' + data.author + '</li><li>描述:' + data.desc + '</li></ul>';
            $("#info").html(tag);
        }
    });
});
</script>
<section id="container">
    <div>
        图书编码:
        <input type="text" name="code" id="code">
        <input type="button" value="查询" id="btn">
    </div>
    <div id="info"></div>
</section>
  • jQuery-ajax的封装
function ajax(url,type,param,dataType,callback){
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    if(type == 'get'){
        url += "?" + 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){
                var data = xhr.responseText;
                if(dataType == 'json'){
                    data = JSON.parse(data);
                }
                callback(data);
            }
        }
    }
}

function ajax(obj){
    // 默认参数
    var defaults = {
        type : 'get',
        data : {},
        url : '#',
        dataType : 'text',
        async : true,
        success : function(data){console.log(data)}
    }
    // 处理形参,传递参数的时候就覆盖默认参数,不传递就使用默认参数
    for(var key in obj){
        defaults[key] = obj[key];
    }
    // 1、创建XMLHttpRequest对象
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    // 把对象形式的参数转化为字符串形式的参数
    /*
    {username:'zhangsan','password':123}
    转换为
    username=zhangsan&password=123
    */
    var param = '';
    for(var attr in obj.data){
        param += attr + '=' + obj.data[attr] + '&';
    }
    if(param){
        param = param.substring(0,param.length - 1);
    }
    // 处理get请求参数并且处理中文乱码问题
    if(defaults.type == 'get'){
        defaults.url += '?' + encodeURI(param);
    }
    // 2、准备发送(设置发送的参数)
    xhr.open(defaults.type,defaults.url,defaults.async);
    // 处理post请求参数并且设置请求头信息(必须设置)
    var data = null;
    if(defaults.type == 'post'){
        data = param;
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    }
    // 3、执行发送动作
    xhr.send(data);
    // 处理同步请求,不会调用回调函数
    if(!defaults.async){
        if(defaults.dataType == 'json'){
            return JSON.parse(xhr.responseText);
        }else{
            return xhr.responseText;
        }
    }
    // 4、指定回调函数(处理服务器响应数据)
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                var data = xhr.responseText;
                if(defaults.dataType == 'json'){
                    // data = eval("("+ data +")");
                    data = JSON.parse(data);
                }
                defaults.success(data);
            }
        }
    }

}
posted @ 2020-09-08 09:01  wing1377  阅读(282)  评论(0)    收藏  举报