Ajax的使用

应用服务器

数据库服务器

 

Ajax、异步的js和xml异步交互,它能使用js访问服务器,而且是异步访问

服务器给客户端的响应一般是整个页面,一个完整的html页面,但在ajax中因为是局部刷新,那么服务器就不用在响应整个页面!而只是数据!

可以是text纯文本,xml,json它是js提供的数据交互格式,它是ajax中最受欢迎

 

 

同步发一个请求就要等到服务器的响应结束,然后才能发第二个请求,中间是卡的过程

刷新的是整个页面

 

异步 发一个请求 无需等待服务器的响应,然后发第二个请求。

可以使用js接收服务器的响应,然后使用js来局部刷新。

 

Ajax的应用场景

百度的搜索框

用户注册校验用户名是否存在

 

优点

增强了用户的体验

性能:应为无需响应整个页面,只响应一部分的页面 服务器省事了

 

Ajax不能应用所有场景

无端的增多了对服务器发送了好多请求。

给服务器制造了好多压力

实例一 get请求

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        System.out.println("Hello ajax!");

        response.getWriter().print("hello,ajax!");

    }

 

    <script type="text/javascript">

        function createXMLHttpRequest(){

            try {

                return new XMLHttpRequest();//大多数的浏览器

            } catch (e) {

                try {

                    return ActiveXObject("Msxml2.XMLHTTP");//ie6.0

                } catch (e) {

                    try {

                        return ActiveXObject("Microsoft.XMLHTTP");//ie5.5或更早的

                    } catch (e) {

                        alert("哥们,你用的是什么浏览器啊!");

                        throw e;

                    }

                }

            }

        }

        window.onload=function(){//在文档加载完毕之后执行

            var btn=document.getElementById("btn1");

            btn.onclick=function(){//给按钮的点击事件注册监听

                /*

                四步操作 获取服务器传来的东西

                */

                //第一步 拿到异步对象

                var xmlHttp=createXMLHttpRequest();

                //第二步 打开与服务器的连接 1请求方式 2请求路径 3是否为异步请求

                xmlHttp.open("GET","<c:url value='/AServlet'/>",true);

                //第三步 发送请求体

                xmlHttp.send(null);//get方式没有请求体,也要写否则火狐不能发送

                //第四步 给异步对象的onreadystatechange注册监听器

                xmlHttp.onreadystatechange=function(){//当状态发生改变时执行

                    if(xmlHttp.readyState==4&&xmlHttp.status==200){

                        //获取服务器的响应

                        var text=xmlHttp.responseText;

                        

                        var h1=document.getElementById("h1");

                        h1.innerHTML=text;

                    }

                    

                };

            };

        };

    </script>

</head>

 

<body>

<!-- 我希望点击这个按钮是将服务器响应的内容 h1标签里输出出来 -->

<button id="btn1">点击这里</button>

<h1 id="h1"></h1>

</body>

Post请求

 

    <script type="text/javascript">

        function createXMLHttpRequest(){

            try {

                return new XMLHttpRequest();//大多数的浏览器

            } catch (e) {

                try {

                    return ActiveXObject("Msxml2.XMLHTTP");//ie6.0

                } catch (e) {

                    try {

                        return ActiveXObject("Microsoft.XMLHTTP");//ie5.5或更早的

                    } catch (e) {

                        alert("哥们,你用的是什么浏览器啊!");

                        throw e;

                    }

                }

            }

        }

        window.onload=function(){//在文档加载完毕之后执行

            var btn=document.getElementById("btn1");

            btn.onclick=function(){//给按钮的点击事件注册监听

                /*

                四步操作 获取服务器传来的东西

                */

                //第一步 拿到异步对象

                var xmlHttp=createXMLHttpRequest();

                //第二步 打开与服务器的连接 1请求方式 2请求路径 3是否为异步请求

                /***********修改post***********/

                xmlHttp.open("POST","<c:url value='/AServlet'/>",true);

                /***********设置请求头 Content-type***********/

                xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

                //第三步 发送请求体

                /***********发送时给出请求体***********/

                xmlHttp.send("username=张三&password=123");//get方式没有请求体,也要写否则火狐不能发送

                //第四步 给异步对象的onreadystatechange注册监听器

                xmlHttp.onreadystatechange=function(){//当状态发生改变时执行

                    if(xmlHttp.readyState==4&&xmlHttp.status==200){

                        //获取服务器的响应

                        var text=xmlHttp.responseText;

                        

                        var h1=document.getElementById("h1");

                        h1.innerHTML=text;

                    }

                    

                };

            };

        };

    </script>

</head>

 

<body>

<!-- 我希望点击这个按钮是将服务器响应的内容 h1标签里输出出来 -->

<button id="btn1">点击这里</button>

<h1 id="h1"></h1>

</body>

 

    public void doPost(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");

        resp.setContentType("text/html;charset=utf-8");

        String username=req.getParameter("username");

        

        System.out.println("(post)Hello ajax!"+username);

        resp.getWriter().print("(post)hello,ajax!"+username);

    }

 

 

校验用户名是否注册过了。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'ajax3.jsp' starting page</title>

 

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

    <script type="text/javascript">

    function createXMLHttpRequest(){

        try {

            return new XMLHttpRequest();//大多数的浏览器

        } catch (e) {

            try {

                return ActiveXObject("Msxml2.XMLHTTP");//ie6.0

            } catch (e) {

                try {

                    return ActiveXObject("Microsoft.XMLHTTP");//ie5.5或更早的

                } catch (e) {

                    alert("哥们,你用的是什么浏览器啊!");

                    throw e;

                }

            }

        }

    }

        window.onload=function(){

            var userEle=document.getElementById("usernameEle");

            userEle.onblur=function(){

                //1得到异步对象

                var xmlHttp=createXMLHttpRequest();

                //2打开连接

                xmlHttp.open("POST","<c:url value='/ValidateUsername'/>",true);

                //3设置请求头

                xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                //4发送请求

                xmlHttp.send("username="+userEle.value);

                //5xmlHttponreadystatechange注册监听

                xmlHttp.onreadystatechange=function(){

                    if(xmlHttp.readyState==4&&xmlHttp.status==200){

                        var text=xmlHttp.responseText;

                        var span=document.getElementById("span");

                        if(text==1){

                            

                            span.innerHTML="用户名已经注册!";

                        }else{

                            span.innerHTML="用户名可用!";

                        }

                        

                    }

                };

            };

        };

    </script>

</head>

 

<body>

This is my JSP page. <br>

<h1>演示用户名是否已经被注册</h1>

<form action="" method="post">

用户名:<input type="text" name="username" id="usernameEle"><span id="span"></span><br>

密码:<input type="password" name="username"><br>

<input type="submit" value="提交">

 

</form>

</body>

</html>

 

 

package com.pcx.web.Servlet;

 

import java.io.IOException;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class ValidateUsername extends HttpServlet {

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        response.setContentType("text/html;charset=utf-8");

        /*

         * 拿到username

         * 判断是否为张三

         *     如果是返回1

         *     如果不是返回0

         */

        String username=request.getParameter("username");

        if ("zhangsan".equalsIgnoreCase(username) ){

            response.getWriter().print("1");

        }else{

            response.getWriter().print("0");

        }

    }

 

}

 

响应内容为Xml

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        String xml="<students>"+

            "<student number='201303014039'>"

            + "<name>张三</name>"

            + "<age>20</age>"

            + "<sex>male</sex>"

            + "</student>"

            + "</students>";

        response.setContentType("text/xml;charset=utf-8");

        response.getWriter().print(xml);

    }

 

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

 

<title>My JSP 'ajax1.jsp' starting page</title>

 

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

    <script type="text/javascript">

        function createXMLHttpRequest(){

            try {

                return new XMLHttpRequest();//大多数的浏览器

            } catch (e) {

                try {

                    return ActiveXObject("Msxml2.XMLHTTP");//ie6.0

                } catch (e) {

                    try {

                        return ActiveXObject("Microsoft.XMLHTTP");//ie5.5或更早的

                    } catch (e) {

                        alert("哥们,你用的是什么浏览器啊!");

                        throw e;

                    }

                }

            }

        }

        window.onload=function(){//在文档加载完毕之后执行

            var btn=document.getElementById("btn1");

            btn.onclick=function(){//给按钮的点击事件注册监听

                /*

                四步操作 获取服务器传来的东西

                */

                //第一步 拿到异步对象

                var xmlHttp=createXMLHttpRequest();

                //第二步 打开与服务器的连接 1请求方式 2请求路径 3是否为异步请求

                xmlHttp.open("GET","<c:url value='/BServlet'/>",true);

                //第三步 发送请求体

                xmlHttp.send(null);//get方式没有请求体,也要写否则火狐不能发送

                //第四步 给异步对象的onreadystatechange注册监听器

                xmlHttp.onreadystatechange=function(){//当状态发生改变时执行

                    if(xmlHttp.readyState==4&&xmlHttp.status==200){

                        //获取服务器的响应

                        var doc=xmlHttp.responseXML;

                    

                        var ele=doc.getElementsByTagName("student")[0];

                        var number=ele.getAttribute("number");

                        var name;

                        var age;

                        var sex;

                        //处理浏览器差异

                        if (window.addEventListener) {//其他浏览器

                            name=ele.getElementsByTagName("name")[0].textContent;

                        alert(name);

                            age=ele.getElementsByTagName("age")[0].textContent;

                            sex=ele.getElementsByTagName("sex")[0].textContent;

                        }else{//ie

                            name=ele.getElementsByTagName("name")[0].text;

                            age=ele.getElementsByTagName("age")[0].text;

                            sex=ele.getElementsByTagName("sex")[0].text;

                        }

                          

                          

                        

                        

                        var text=number+","+name+","+age+","+sex;

                        document.getElementById("h1").innerHTML=text;

                    }

                    

                };

            };

        };

    </script>

</head>

 

<body>

<!-- 我希望点击这个按钮是将服务器响应的内容 h1标签里输出出来 -->

<button id="btn1">点击这里</button>

<h1 id="h1"></h1>

</body>

</html>

 

 

省市联动的案例

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/chengzhipcx/p/5018924.html