AJAX请求

  • 1.什么是AJAX请求
  • 2.javaScript原生的Ajax请求
  • 3.JQuery 中的Ajax请求
  • 1. $.ajax方法
  • 2.$.get方法和 $.post方法
  • 3. Jquery的$.getJSON方法
  • 4.表单序列化 serialize()


1.什么是AJAX请求

AJAX请求是”Asynchronous JavaScript And XML“(异步javascript和xml),是指一种创建交互式网页应用使用的网页开发技术。
ajax是一种浏览器通过js异步发起的请求,局部更新页面的技术。

ajax的局部更新 ,浏览器地址栏不会发生变化,
局部更新不会舍弃原来更新的内容

2.javaScript原生的Ajax请求

原生的 Ajax 请求,
1、我们首先要创建 XMLHttpRequest 对象
2、调用 open 方法设置请求参数
3、调用 send 方法发送请求
4、在 send 方法前绑定 onreadystatechange 事件,处理请求完成后的操作。
1)创建一个页面发送请求,

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="pragma" content="no-cache" />
		<meta http-equiv="cache-control" content="no-cache" />
		<meta http-equiv="Expires" content="0" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Insert title here</title>
		<script type="text/javascript" src="script/jquery-1.7.2.js"></script>
		<script type="text/javascript">
			//在这里使用JavaScript语言发起ajax请求,访问服务器AjaxServlet中javaScriptAjax方法
			function ajaxRequest() {
// 				1、我们首先要创建XMLHttpRequest
				var xmlHttpRequest = new XMLHttpRequest();
// 				2、调用open方法设置请求参数
				xmlHttpRequest.open("GET","ajaxServlet?action=javaScriptAjax&a="+new Date(), true);//同步和异步
	//			4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
				xmlHttpRequest.onreadystatechange = function () {
					if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
						alert("收到服务器返回的数据:"+ xmlHttpRequest.responseText);
						var jsonObj = JSON.parse(xmlHttpRequest.responseText);
						//把相应的数据显示在页面上
						document.getElementById("div01").innerHTML="编号:"+jsonObj.id+"名字:"+jsonObj.name;
					}
				}
// 				3、调用send方法发送请求
				xmlHttpRequest.send();

				alert("我是最后一行的代码。")

			}
		</script>
	</head>
	<body>	
		<button onclick="ajaxRequest()">ajax request</button>
		<div id="div01">
		</div>
	</body>
</html>

2)创建一个ajaxServlet程序接收请求

package com.atguigu.Servlet;

import com.atguigu.pojo.Person;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AjaxServlet extends BaseServlet {
    protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ajax请求过来了");
        Person person = new Person(1, "zhaochen");
        Gson gson = new Gson();
        String toJson = gson.toJson(person);
        resp.getWriter().write(toJson);

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3)web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">



    <servlet>
        <servlet-name>AjaxServlet</servlet-name>
        <servlet-class>com.atguigu.Servlet.AjaxServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AjaxServlet</servlet-name>
        <url-pattern>/ajaxServlet</url-pattern>
    </servlet-mapping>
</web-app>

通过上面的代码我们发现。编写原生的 JavaScript 我们自己要写很多的代码。而且还要考虑浏览器兼容问题。所以使用起来非常的不方便。那我们工作之后。怎么处理 Ajax 请求呢。我们一般会使用 JavaScript 的框架来解决这个问 题,比如说我们前面学到的 Jquery 框架。它就有很好的ajax解决方案。

3.JQuery 中的Ajax请求

1. $.ajax方法

url 表示请求的地址
type 表示请求的类型GET或POST
data 表示发送给服务器的数据
格式有两种:
1.name=value&name=value
2.{key:value}
success 请求响应,响应的回调函数
dataType 相应的数据类型
常用的数据类型有:
text表示纯文本,xml 表示xml数据,json表示json数据

$(function(){
				// ajax请求
				$("#ajaxBtn").click(function(){

                      $.ajax({
						  url:"http://localhost/ajaxServlet",
						  // data:"action = jQueryAjax",
                           data:{action : "jQueryAjax"},
						  type:"GET",
						  success : function (data) {
							  alert("服务器返回回来的参数是:"+data);
                            // var JsonObj = JSON.parse(data);
                             $("#msg").html("编号:"+JsonObj.id+"名字:"+JsonObj.name)
						  },
						  dataType:"json"
					  });
				});
package com.atguigu.Servlet;

import com.atguigu.pojo.Person;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class AjaxServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决post请求中文乱码问题
        // 一定要在获取请求参数之前调用才有效
        req.setCharacterEncoding("UTF-8");
        // 解决响应中文乱码
        resp.setContentType("text/html; charset=UTF-8");
        String action = req.getParameter("action");
        try {
            // 获取action业务鉴别字符串,获取相应的业务 方法反射对象
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            System.out.println(method);
            // 调用目标业务 方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);// 把异常抛给Filter过滤器
        }
    }

    protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ajax请求过来了");
        Person person = new Person(1, "zhaochen");
        Gson gson = new Gson();
        String toJson = gson.toJson(person);
        resp.getWriter().write(toJson);
    }
    protected void jQueryAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("jQuery请求过来了");
        Person person = new Person(1, "zhaochen");
        Gson gson = new Gson();
        String toJson = gson.toJson(person);
        resp.getWriter().write(toJson);

    }




}

2.$.get方法和 $.post方法

url:请求的 URL 地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text。

// ajax--get请求
				$("#getBtn").click(function(){
					$.get("http://localhost/ajaxServlet","action = jQueryGet",function (data){
						$("#msg").html("get 编号:"+JsonObj.id+"名字:"+JsonObj.name);
					},"json")

					
				});
				
				// ajax--post请求
				$("#postBtn").click(function(){
					$.get("http://localhost/ajaxServlet","action = jQueryPost",function (data){
						alert("hello");
					},"json")
					
				});

3. Jquery的$.getJSON方法

url:待载入页面的url地址
data:待发送的key/value参数
callback:载入成功时回调函数

// ajax--getJson请求
			$("#getJSONBtn").click(function(){
            $.getJSON("http://localhost/ajaxServlet","action = jQueryGetJson",function (json){
            	alert(data);
			});
			});

4.表单序列化 serialize()

serialize() 可以把表单项的所有内容都获取到,并以name=value&name=value的形式进行拼接

// ajax请求
				$("#submit").click(function(){
					alert($("#from01").serialize());
					$.getJSON("http://localhost/ajaxServlet","action =jQuerySerialize ",function (json){
						alert("serialize 序号:"+json.id+"姓名:"+json.name);
					})
				});