深入理解Ajax技术

Ajax

get和post请求区别

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

ajax.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>



    Title










AjaxServlet
package com.wanggs.web;

/**
 * @author Wgs
 * @version 1.0
 * @create:2018/05/28
 */
@WebServlet("/ajax")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("发出ajax请求!!!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("发出post请求!!!");
    }
}


测试

http://localhost:8085/ajax.jsp

/ajax
发出ajax请求!!!


回调函数

package com.wanggs.web;



/**
 * @author Wgs
 * @version 1.0
 * @create:2018/05/28
 */
@WebServlet("/ajax")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        java.lang.String name = req.getParameter("name");
        //URL中含有中文
        name = new String(name.getBytes("ISO8859-1"),"UTF-8");
        System.out.println(name+"发出ajax请求!!!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 表单提交(POST) 含有中文
        req.setCharacterEncoding("UTF-8");
        // 客户端响应含有中文
        resp.setCharacterEncoding("UTF-8");
        // 设置响应内容纯字符串
        resp.setContentType("text/plain;charset=UTF-8");
        String name = req.getParameter("name");
        PrintWriter writer = resp.getWriter();
        if ("tom".equals(name)){
            System.out.println("账号占用!!");
            writer.append("不能用");
        }else{
            System.out.println("可以用!!!");
            writer.append("可用");
        }
        writer.flush();
        writer.close();
    }
}

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>



    Title


    
    
    
测试

http://localhost:8085/ajax.jsp


封装Ajax

var ajax = {};
ajax.sendPost = function(obj){
    //创建XMLHttpRequest对象
    function createXmlHttp() {
        var xmlHttp = null;
        if(window.ActiveXObject) {
            //IE
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            xmlHttp = new XMLHttpRequest();
        }
        return xmlHttp;
    }
    var xmlHttp = createXmlHttp;
    xmlHttp.open("post",obj.url);
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                var result = xmlHttp.responseText;
                obj.success(result);
            } else {
                obj.error();
            }
        }
    };
    xmlHttp.send(obj.data);
};

测试

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>



    Title


    
    
    

get请求缓存

  • 加无意义参数

"&_="+new Date().getTime());

    function sendGet(name) {
                //1. 获取Ajax引擎
                var xmlHttp = createXmlHttp();
                //2. 指定请求方式(GET|POST)和请求地址
                //xmlHttp.open("get","/ajax?name="+name+"&_="+new Date().getTime());
                xmlHttp.open("get","/ajax?name="+name);
                //3. 发出请求
                xmlHttp.send();
            }
  • 设置响应头
//声明禁止浏览器缓存结果的响应头
        resp.setHeader("pragma","no-cache");
        resp.setHeader("cache-control","no-cache");
        resp.setHeader("expries","0");

什么是ajax跨域

ajax跨域的原理

  • ajax出现请求跨域错误问题,主要原因就是因为浏览器的“同源策略”,可以参考

  • 浏览器同源政策及其规避方法(阮一峰)

ajax跨域的表现

第一种现象 No 'Access-Control-Allow-Origin' header is present on the requested resource,并且The response had HTTP status code 404
image.png
出现这种情况的原因如下:

本次ajax请求是“非简单请求”,所以请求前会发送一次预检请求(OPTIONS)
服务器端后台接口没有允许OPTIONS请求,导致无法找到对应接口地址

第二种现象 No 'Access-Control-Allow-Origin' header is present on the requested resource,并且The response had HTTP status code 405

[图片上传失败...(image-7191b-1528122021897)]

第三种现象:No 'Access-Control-Allow-Origin' header is present on the requested resource,并且status 200

[图片上传失败...(image-231d7d-1528122021897)]


servlet json

package com.wanggs.web;


/**
 * @author Wgs
 * @version 1.0
 * @create:2018/06/02
 */
@WebServlet("/json")
public class JsonDataServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;character=UTF-8");
        String json = "{\"name\":\"tom\",\"id\":1}";
        PrintWriter out = resp.getWriter();
        out.append(json);
        out.flush();
        out.close();
    }
}

测试

http://localhost:8085/json
{name:"tom",id:1}

响应客户端

package com.wanggs.web;



/**
 * @author Wgs
 * @version 1.0
 * @create:2018/06/02
 */
@WebServlet("/json")
public class JsonDataServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;character=UTF-8");
       // String json = "{\"name\":\"tom\",\"id\":1}";
        User user = new User();
        user.setName("tom");
        user.setAge(12);
        User user1 = new User();
        user1.setName("jack");
        user1.setAge(32);
        List users = Arrays.asList(user,user1);
        // Gson
    /*    Gson gson = new Gson();
        String json = gson.toJson(user);*/


        String json = JSONObject.toJSONString(users);
        PrintWriter out = resp.getWriter();
        out.append(json);
        out.flush();
        out.close();
    }
}

jsp

<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>



    
    Document
    







测试

http://localhost:8085/json.jsp

ajax json

<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    Document


    
    
    



form 表单序列化 css3动画

jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title






servlet
package com.wanggs.web.jq;


/**
 * @author Wgs
 * @version 1.0
 * @create:2018/06/03
 */
@WebServlet("/logins")
public class LoginsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/jq/login.jsp").forward(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        Map result = new HashMap<>();
        if ("tom".equals(name) && "123123".equals(password)){
            result.put("state","success");
        }else {
           result.put("state","error");
           result.put("message","账号或者密码错误");
        }


        Writer out = resp.getWriter();
        out.append(JSONObject.toJSONString(result));
        out.flush();
        out.close();
    }
}

表单序列化
image.png
css3动画 抖一抖
Animate.css
image.png
登陆动画
image.png
image.png

表单验证

image.png
  $('#loginBtn').click(function () {
            $("#fm").submit();

        });

        $('#fm').validate({
            errorElement:"span",
            errorClass:"text-danger",
            rules:{
                name:{
                    required:true
                },
                password:{
                    required:true
                }
            },
            messages:{
                name:{
                    required:"请输入账号"
                },
                password:{
                    required:"请输入密码"
                }
            },
            submitHandler:function(){
                $.ajax({
                    url : "/logins",
                    type : "post",
                    data : $("#fm").serialize(),
                    beforeSend:function(){
                        $("#loginBtn").append($("")).attr("disabled","disabled");
                    },
                    complete:function(){
                        $("#loginBtn").html("登录").removeAttr("disabled");
                    },
                    success : function(data) {
                        if(data.state == "error") {
                            alert(data.message);
                        } else {
                            window.location.href = "/jq/demo1.jsp";
                        }
                    },
                    error : function() {
                        alert("服务器错误");
                    }
                });
            }
        });


异步验证

image.png
image.png
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    Document
    
    
    


servlet
package com.wanggs.web.jq;


/**
 * @author Wgs
 * @version 1.0
 * @create:2018/06/04
 */
@WebServlet("/checkemail")
public class CheckEmailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mail = req.getParameter("mail");

        System.out.println("EMail:" + mail);

        PrintWriter out = resp.getWriter();
        if("[email protected]".equals(mail)) {
            out.print("false");
        } else {
            out.print("true");
        }

        out.flush();
        out.close();

    }
}


getJson跨域请求 有道词典翻译

<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    Document


 

你可能感兴趣的:(深入理解Ajax技术)