jsp页面
<%@ page import="java.util.Date" %><%--
Created by IntelliJ IDEA.
User: ChengLong
Date: 2021/8/24
Time: 10:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>使用JavaScript发送ajax的get请求</title>
</head>
<script>
/*点击id=jsAJAXget按钮,发送异步请求*/
window.onload=function () {
//1、获取id=jsAJAXget按钮
var jsAJAXget = document.getElementById("jsAJAXget");
jsAJAXget.onclick = function () {
//2、创建XMLHttpRequest
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//3、设置请求信息
/*
* open(method, url, async)
规定请求
method:请求类型 GET 或 POST
url:文件位置
async:true(异步)或 false(同步) 默认true
* */
xhttp.open("get", "/day17/JsAjaxGetServlet?name=汤姆&pwd=123")
//4、发送请求
xhttp.send();
//5、获取响应信息
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var str = this.responseText;
var msg = document.getElementById("msg");
msg.innerHTML = str;
}
}
}
}
</script>
<body>
<%=new Date() %>
<button id="jsAJAXget">使用JavaScript发送ajax的gat请求</button>
<h2 style="color: blue" id="msg"></h2>
</body>
</html>
servlet页面
import javax.servlet.ServletException;
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.io.PrintWriter;
/**
* @author: ChengLong
* @version: 11.0.2
* @datetime: 2021/8/24 10:30
*/
@WebServlet("/JsAjaxGetServlet")
public class JsAjaxGetServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String name = req.getParameter("name");
String pwd = req.getParameter("pwd");
System.out.println(name+"==="+pwd);
//响应流对象
PrintWriter writer = resp.getWriter();
writer.print("我爱Java");
}
}
jsp页面
<%@ page import="java.util.Date" %><%--
Created by IntelliJ IDEA.
User: ChengLong
Date: 2021/8/24
Time: 11:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>使用JavaScript发送ajax的post请求</title>
</head>
<script>
/*点击id=jsAJAXpost按钮,发送异步请求=*/
window.onload=function () {
//1、获取id=jsAJAXget按钮
var jsAJAXget = document.getElementById("jsAJAXpost");
jsAJAXget.onclick = function () {
//2、创建XMLHttpRequest
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//3、设置请求信息
/*
* open(method, url, async)
规定请求
method:请求类型 GET 或 POST
url:文件位置
async:true(异步)或 false(同步) 默认true
* */
xhttp.open("post", "/day17/JsAjaxPostServlet")
//4、发送请求
//对请求体中内容进行编码
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("name=汤姆&pwd=123");
//5、获取响应信息
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var str = this.responseText;
//把str转为json
var strObj = JSON.parse(str);
alert(strObj.name);
var msg = document.getElementById("msg");
msg.innerHTML = str;
}
}
}
}
</script>
<body>
servlet页面
import javax.servlet.ServletException;
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.io.PrintWriter;
/**
* @author: ChengLong
* @version: 11.0.2
* @datetime: 2021/8/24 11:02
*/
@WebServlet("/JsAjaxPostServlet")
public class JsAjaxPostServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String pwd = req.getParameter("pwd");
System.out.println(name+"==="+pwd);
//响应流对象
PrintWriter writer = resp.getWriter();
String json = "{\"name\":\"张三\",\"age\":18,\"性别\":\"男\",\"citys\":[\"武汉\",\"北京\"]}";
writer.print(json);
}
}
json语法格式
定义json对象
var json1={“name”:”张三”,”age”:18,”ischeck”:true,”citys”:[“武汉”,”北京”]};
var json2={"stu1":{"name":"张三","age":18},
"stu2":{"name":"唐僧","age":50,"hobby":"念经"},
"stu3":{"name":"八戒","age":500,"like":[
{"name":"高翠兰","age":16},
{"name":"嫦娥","age":300}]
},
}
语法
语法
ObjectMapper om=new ObjectMapper();
String jsonStr=om.writeValueAsString(对象); //得到json字符串
public void test1() throws JsonProcessingException {
Book book = new Book(1,"css入门",80,"无");
//把book对象转为json数据
ObjectMapper objectmapper = new ObjectMapper();
String json = objectmapper.writeValueAsString(book);
System.out.println(json);
}
public void test2() throws JsonProcessingException {
List<Book> list = new ArrayList<>();
list.add(new Book(1,"css入门",80,"无"));
list.add(new Book(2,"java入门",90,"无"));
list.add(new Book(3,"js入门",50,"无"));
//把list对象转为json数据
ObjectMapper objectmapper = new ObjectMapper();
String json = objectmapper.writeValueAsString(list);
System.out.println(json);
}
语法
public void test3() throws JsonProcessingException {
HashMap<String,Book> map = new HashMap<>();
map.put("aa",new Book(1,"css入门",80,"无"));
map.put("bb",new Book(1,"java入门",90,"无"));
map.put("cc",new Book(1,"js入门",50,"无"));
//把map对象转为json数据
ObjectMapper objectmapper = new ObjectMapper();
String json = objectmapper.writeValueAsString(map);
System.out.println(json);
}
jQuery.ajax(url,[settings])
type:请求的方式get/post
url:请求地址
data:请求携带的数据,可以是json对象{"属性":"属性值"},也可以是普通的请求数据类型:属性名称=属性值
dataType:是响应的数据类型,可以是文本也可以是xml或者json,默认文本
success响应成功后的回调函数,响应数据会存放在方法的参数中
error:程序出现异常后会调用error中的方法
beforeSend:请求之前调用方法
complete:响应完成后调用
jsp页面
<%--
Created by IntelliJ IDEA.
User: ChengLong
Date: 2021/8/24
Time: 14:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>使用jQuery发送ajax请求</title>
</head>
<script src="../js/jquery-1.7.2.js"></script>
<script>
/*回调函数
如果要处理$.ajax()得到的数据,则需要使用回调函数。beforeSend、error、dataFilter、success、complete。
beforeSend 在发送请求之前调用,并且传入一个XMLHttpRequest作为参数。
error 在请求出错时调用。传入XMLHttpRequest对象,描述错误类型的字符串以及一个异常对象(如果有的话)
dataFilter 在请求成功之后调用。传入返回的数据以及"dataType"参数的值。并且必须返回新的数据(可能是处理过的)传递给success回调函数。
success 当请求之后调用。传入返回后的数据,以及包含成功代码的字符串。
complete 当请求完成之后调用这个函数,无论成功或失败。传入XMLHttpRequest对象,以及一个包含成功或错误代码的字符串*/
$(function () {
$("#btn").click(function () {
//发送ajax异步请求
$.ajax({
//请求类型
type:"get",
//请求地址
url:"/day17/JqueryAjaxServlet",
// data:"name=张三&age=18",
//请求参数
data:{name:"张三",age:18},
//如果值为json,会自动把后台返回的json对象
dataType:"json",
//后台返回响应数据,会自动赋值到回调函数的result中,result就是后台返回响应的数据
success:function (result) {
alert(result.title);
alert(JSON.stringify(result));
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status)
alert(textStatus)
alert(errorThrown)
},
beforeSend:function () {
//发送请求之前调用该方法
//用户点击按钮后,禁用按钮
$("#btn").attr("disabled","disabled")
},
complete:function () {
//响应成功后,解除禁用
$("#btn").removeAttr("disabled")
}
})
})
})
</script>
<body>
<button id="btn">使用jQuery发送ajax请求</button>
</body>
</html>
servlet页面
import bean.Book;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author: ChengLong
* @version: 11.0.2
* @datetime: 2021/8/24 15:02
*/
@WebServlet("/JqueryAjaxServlet")
public class JqueryAjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
//获取请求数据
String name = req.getParameter("name");
String age = req.getParameter("age");
System.out.println(name+"==="+age);
//模拟空指针异常
/* String x = null;
if (x.equals("ssss")){
System.out.println(111);
}*/
//模拟网络延迟
/*try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
ObjectMapper objectMapper = new ObjectMapper();
//把book对象转为json字符串
Book book = new Book(1,"AJAX",80,"无");
String json = objectMapper.writeValueAsString(book);
//把json字符串响应给浏览器
resp.getWriter().print(json);
}
}
$.get(url,[data],[callback],[type]??
url:请求地址
data请求携带的数据,可以是json对象{"属性":"属性值"},也可以是普通的请求数据类型:属性名称=属性值
type:响应数据类型,可以是文本也可以是xml或者json,默认文本
callback:响应成功后的回调函数,响应数据会存放方法的参数中
jsp页面
<%--
Created by IntelliJ IDEA.
User: ChengLong
Date: 2021/8/24
Time: 15:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="../js/jquery-1.7.2.js"></script>
<script>
/* url,[data],[callback],[type]
url:待载入页面的URL地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。*/
$(function () {
$("#btn").click(function () {
// $.get("/JqueryAjaxGetServlet02","name=北京&age=18")
// $.get("/JqueryAjaxGetServlet02", {"city": "北京", age: 18}, function (data) {}, "json")
var url = "/day17/JqueryAjaxGetServlet02";
var data = {"city": "北京", age: 18};
var callback=function (result) {
alert(result);
};
var type="json";
$.get(url,data,callback,type);
})
})
</script>
</head>
<body>
<button id="btn">使用jQuery发送ajax的get请求</button>
</body>
</html>
servlet页面
import bean.Book;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author: ChengLong
* @version: 11.0.2
* @datetime: 2021/8/24 15:37
*/
@WebServlet("/JqueryAjaxGetServlet02")
public class JqueryAjaxGetServlet02 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String city = req.getParameter("city");
String age = req.getParameter("age");
System.out.println(city+"==="+age);
//返回响应数据
ObjectMapper objectMapper = new ObjectMapper();
//把book对象转为json字符串
Book book = new Book(1,"AJAX",80,"无");
String json = objectMapper.writeValueAsString(book);
//把json字符串响应给浏览器
resp.getWriter().print(json);
}
}
jsp页面
<%--
Created by IntelliJ IDEA.
User: ChengLong
Date: 2021/8/24
Time: 15:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="../js/jquery-1.7.2.js"></script>
<script>
/* url,[data],[callback],[type]
url:待载入页面的URL地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。*/
$(function () {
$("#btn").click(function () {
// $.post("/JqueryAjaxGetServlet02","name=北京&age=18")
// $.post("/JqueryAjaxGetServlet02", {"city": "北京", age: 18}, function (data) {}, "json")
var url = "/day17/JqueryAjaxGetServlet03";
var data = {"city":"北京", age:18};
var callback=function (result) {
//JSON转换为字符串
alert(JSON.stringify(result));
};
var type="json";
$.post(url,data,callback,type);
})
})
</script>
</head>
<body>
<button id="btn">使用jQuery发送ajax的post请求</button>
</body>
</html>
servlet页面
import bean.Book;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author: ChengLong
* @version: 11.0.2
* @datetime: 2021/8/24 15:47
*/
@WebServlet("/JqueryAjaxGetServlet03")
public class JqueryAjaxPostServlet03 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
String city = req.getParameter("city");
String age = req.getParameter("age");
System.out.println(city+"==="+age);
//返回响应数据
ObjectMapper objectMapper = new ObjectMapper();
//把book对象转为json字符串
Book book = new Book(1,"AJAX入门使用",80,"无");
String json = objectMapper.writeValueAsString(book);
//把json字符串响应给浏览器
resp.getWriter().print(json);
}
}
原文:https://www.cnblogs.com/chenglong0201/p/15182605.html