Java CommunityJava学习笔记Java 杂谈

AJAX框架概述

2017-04-20  本文已影响188人  奋斗的老王

一)什么是JavaScript

二)JS中的三种类型

1)基本类型:number,string,boolean

        var num = 100;
        var str = "哈哈";
        var flag = false;
        window.alert(num);
        window.alert(str);
        window.alert(flag);

2)特殊类型:null,undefined

        var array = null;
        var student;
        alert(array);
        alert(student);

3)复合类型:函数,对象,数组

三)JS中有三种定义函数的方式

1)正常方式 : function mysum(num1,num2){return num1+num2;}

  function mysum(num1,num2){
    return num1 + num2;
}
var myresult = mysum(100,200);
alert("myresult="+myresult);

2)构造器方式:new Function("num1","num2","return num1+num2;")

var youresult = new Function("num1","num2","return num1+num2");
alert( youresult(1000,2000) );

3)直接量或匿名或无名方式:var mysum = function(num1,num2){return num1+num2;}

var theyresult = function(num1,num2){
    return num1 + num2; 
}
alert( theyresult(10000,20000) );

四)JS中有四种对象

1)内置对象 :Date,Math,String,Array

var str = new Date().toLocaleString();
window.document.write("<font size='44' color='red'>"+str+"</font>");

2)自定义对象:Person,Card,。。。

        function Student(id,name,sal){
            //this指向s引用
            this.id = id;
            this.name = name;
            this.sal = sal;
        }
        var s = new Student(1,"波波",7000);
        document.write("编号:" + s.id + "<br/>");
        document.write("姓名:" + s.name + "<br/>");
        document.write("薪水:" + s.sal + "<br/>");

3)浏览器对象: window,document,status,location,history。。。

function myrefresh(){
            window.history.go(0);
        }

4)ActiveX对象:ActiveXObject("Microsoft.XMLHTTP")

五)演示JS对象的属性,方法和事件的使用

1)window.location.href
2)form.submit()
3)inputElement.onblur = 函数
4)document.createElement(“img”)
5)imgElement.style.width/height

六)回顾传统Web应用请求和响应特点【显示当前时间】

1)请求:浏览器以HTTP协议的方式提交请求到服务器
2)响应:服务器以HTTP协议的方式响应内容到浏览器

    当前时间:<span>${requestScope.str}</span><br/>
    <input type="button" value="同步方式提交"/>
    <script type="text/javascript">
        //定位button按钮,同时添加单击事件
        document.getElementsByTagName("input")[0].onclick = function(){
            var url = "${pageContext.request.contextPath}/TimeServlet?id="+new Date().getTime();
            window.location.href = url; 
        }
    </script>
public class TimeServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        System.out.println("TimeServlet::doGet");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdf.format(new Date());
        request.setAttribute("str",str);
        request.getRequestDispatcher("/06_time.jsp").forward(request,response);
    }
}

七)什么是AJAX(Asynchronous异步的JS和XML) & 工作原理与特点

1)什么是同步:请求1->响应1->请求2->响应2 ( Web1.0时代 )

2)什么是异步:(Web2.0时代)

3)什么是AJAX

4)不用刷新整个页面便可与服务器通讯的办法有:

5)AJAX工作原理

6)AJAX包含的技术

7)AJAX开发步骤
1. 创建AJAX异步对象,例如:createAJAX()
2. 准备发送异步请求,例如:ajax.open(method,url)
3. 如果是POST请求的话,一定要设置AJAX请求头,例如:ajax.setRequestHeader(); 如果是GET请求的话,无需设置设置AJAX请求头
4. 真正发送请求体中的数据到服务器,例如:ajax.send()
5. AJAX不断的监听服务端响应的状态变化,例如:ajax.onreadystatechange,后面写一个无名处理函数
6. 在无名处理函数中,获取AJAX的数据后,按照DOM规则,用JS语言来操作Web页面

8)AJAX适合用在什么地方

9)为什么使用AJAX?

八)AJAX应用

1)无需刷新整个Web页面显示服务器响应的当前时间(text/html;charset=UTF-8)
当前时间:<span></span>

<input type="button" value="异步方式提交"/>

<script type="text/javascript">
        //定位button按钮,同时添加单击事件
        document.getElementsByTagName("input")[0].onclick = function(){
            //NO1)创建AJAX异步对象(每个浏览器内置的,无需第三方jar包)
            var ajax = createAJAX();//0
            //NO2)AJAX异步对象准备发送请求
            var url = "${pageContext.request.contextPath}/TimeServletAjax?id="+new Date().getTime();
            var method = "GET";
            ajax.open(method,url);//1
            //NO3)AJAX异步对象真正发送请求体的数据到服务器,如果请求体无数据的话,用null表示
            var content = null;
            ajax.send(content);//2
            
            //----------------------------------------等待
            
            //NO4)AJAX异步对象不断监听服务端状态的变化,只有状态码变化了,方可触发函数
            //0-1-2-3-4,这些是可以触发函数的
            //4-4-4-4-4,这些是不可以触发函数的
            //以下这个函数是服务器来触发的,不是程序员触发的,这和onclick是不一样的
            ajax.onreadystatechange = function(){
                //如果AJAX状态码为4
                if(ajax.readyState == 4){
                    //如果服务器响应码是200
                    if(ajax.status == 200){
                        //NO5)从AJAX异步对象中获取服务器响应的结果
                        var str = ajax.responseText;
                        //NO6)按照DOM规则,将结果动态添加到web页面指向的标签中
                        document.getElementsByTagName("span")[0].innerHTML = str;
                    }
                }
            }
        } 
    </script>
public class TimeServletAjax extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdf.format(new Date());
        //注意:在Web2.0时代,即异步方式下,不能用转发或重定向
        //因为:转发或重定向会引起浏览器全部刷新,而不是局部刷新
        //所以得用以输出流的方式将服务器的结果输出到浏览器
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(str);
        pw.flush();
        pw.close();
    }
}

2)基于HTML,以GET或POST方式,检查注册用户名是否在数据库中已存在(text/html;charset=UTF-8)

    输入用户名[POST]:<input type="text" maxlength="8"/>光标移出后,立刻显示结果
    <hr/>
    <div></div>
public class RegisterServletPost extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String tip = "images/MsgSent.gif";
        if("杰克".equals(username)){
            tip = "images/MsgError.gif";
        }
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(tip);
        pw.flush();
        pw.close();
    }
}

3)基于XML,以POST方式,完成省份-城市二级下拉联动
(text/xml;charset=UTF-8)

    <select id="province" style="width:111px">
        <option>选择省份</option>
        <option>广东</option>
        <option>湖南</option>
        <option>湖北</option>
    </select>
    
    <select id="city" style="width:111px">
        <option>选择城市</option>
    </select>
<script type="text/javascript">
        //定位省份下拉框,同时添时内容改变事件
        document.getElementById("province").onchange = function(){
            //清除城市下拉框中的内容除第一项外
            var citySelectElement = document.getElementById("city");
            citySelectElement.options.length = 1;
            //获取选中的省份
            var i = this.selectedIndex;
            var optionElement = this[i];
            var province = optionElement.innerHTML;
            //如果不是"选择省份"的话
            if("选择省份" != province){
                //NO1)
                var ajax = createAJAX();
                //NO2)
                var method = "POST";
                var url = "${pageContext.request.contextPath}/ProvinceCityServlet?id="+new Date().getTime();
                ajax.open(method,url);
                ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
                //NO3)
                var content = "province="+province;
                ajax.send(content);
                
                //-------------------------------------------------
                
                //NO4)
                ajax.onreadystatechange = function(){
                    if(ajax.readyState == 4){
                        if(ajax.status == 200){
                            //NO5)
                            var xmlDocument = ajax.responseXML;
                            //NO6)按照dom规则,解析xml文件中的所有内容
                            var cityElementArray = xmlDocument.getElementsByTagName("city");
                            var size = cityElementArray.length;                         
                            for(var i=0;i<size;i++){
                                var cityElement = cityElementArray[i];
                                //innerHTML只能用于html和jsp页面,不能用于xml页面
                                //在xml页面我们通常用firstChild.nodeValue去替代innerHTML
                                var city = cityElement.firstChild.nodeValue;
                                //<option></option>
                                var optionElement = document.createElement("option");
                                //<option>广州</option>
                                optionElement.innerHTML = city;
                                //<select id="city" style="width:111px"><option>广州</option></select>
                                citySelectElement.appendChild(optionElement);
                            }
                        }
                    }
                }
            }
        }
    </script>
public class ProvinceCityServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        this.doPost(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String province = request.getParameter("province");
        
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write("<?xml version='1.0' encoding='UTF-8'?>");
        pw.write("<root>");
        
        if("广东".equals(province)){
            pw.write("<city>广州</city>");
            pw.write("<city>深圳</city>");
            pw.write("<city>中山</city>");
            pw.write("<city>珠海</city>");
        }else if("湖南".equals(province)){
            pw.write("<city>长沙</city>");
            pw.write("<city>株洲</city>");
            pw.write("<city>张家界</city>");
        }else if("湖北".equals(province)){
            pw.write("<city>武汉</city>");
            pw.write("<city>黄岗</city>");
        }
        
        pw.write("</root>");
        pw.flush();
        pw.close();
    }
}

4)验证码检查(text/html;charset=UTF-8)

    <form>
        验证码:
        <input type="text" maxlength="4" size="4"/>
        ![](image.jsp)
        <input type="button" value="看不清" size="2"/>
        <span></span>
    </form>
<script type="text/javascript">
        //定位按钮,同时添加单击事件
        document.getElementsByTagName("input")[1].onclick = function(){
            //定位img标签,修改src属性
            document.images[0].src = "image.jsp?id="+new Date().getTime();
            //清空span标签中的内容
            var spanElement = document.getElementsByTagName("span")[0];
            spanElement.innerHTML = "";
            //清空文本框中的内容
            document.getElementsByTagName("input")[0].value = "";
        }
    </script>
    
    <script type="text/javascript">
        //定位文本框,同时添加键盘弹起事件
        document.getElementsByTagName("input")[0].onkeyup = function(){
            //获取输入的验证码
            var checkcode = this.value;
            //去空格
            checkcode = trim(checkcode);
            //获取验证码的长度
            var size = checkcode.length;
            //如果长度为4
            if(size == 4){
                //NO1)
                var ajax = createAJAX();
                //NO2)
                var method = "POST";
                var url = "${pageContext.request.contextPath}/CheckcodeServlet?id="+new Date().getTime();
                ajax.open(method,url);
                ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
                //NO3)
                var content = "checkcode=" + checkcode; 
                ajax.send(content);
                
                //--------------------------------------------
                
                //NO4)
                ajax.onreadystatechange = function(){
                    if(ajax.readyState == 4){
                        if(ajax.status == 200){
                            //NO5)
                            var imagePath = ajax.responseText;
                            
                            //NO6)
                            var imgElement = document.createElement("img");
                            imgElement.src = imagePath;
                            imgElement.style.width = "14px";
                            imgElement.style.height = "14px";
                            var spanElement = document.getElementsByTagName("span")[0];
                            spanElement.innerHTML = "";
                            spanElement.appendChild(imgElement);
                        }
                    }
                }
            }else{
                //清空span标签中的内容
                var spanElement = document.getElementsByTagName("span")[0];
                spanElement.innerHTML = "";
            }
        }
    </script>
public class CheckcodeServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //获取客户端输入的验证码
        String checkcodeClient = request.getParameter("checkcode");
        //获取服务端产生的验证码 
        HttpSession httpSession = request.getSession();
        String checkcodeServer = (String) httpSession.getAttribute("CHECKNUM");
        //二个验证码进行比较
        String tip = "images/MsgError.gif";
        if(checkcodeClient!=null && checkcodeServer!=null && checkcodeClient.equals(checkcodeServer)){
            tip = "images/MsgSent.gif";
        }
        //以流的方式输出tip变量
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(tip);
        pw.flush();
        pw.close();
    }
}

九)XMLHttpRequest(即AJAX对象, 常用的事件, 方法, 属性)

1)事件:

2)属性:

上述5种状态不是所有浏览器都相同,但状态4每种浏览器都相同

3)方法:

十)数据载体

1)HTML

2)XML

3)JSON + struts2框架

上一篇下一篇

猜你喜欢

热点阅读