Ajax的使用流程
- 创建XmlHttpRequest对象
- XMLHttpRquest用于在后台与服务器交换数据,是AJAX的核心
- XMLHttpRequest并不是W3C的标准,不通风浏览器创建发送不同
- 发送Ajax请求
- xmlhttp.open() 用于创建请求
- mxlhttp.send() 用于发送请求
- 处理服务器响应
- xmlhttp.onreadystatechange(); 事件用于监听AJAX的执行过程
- xmlhttp.readyState 属性说明XMLHttpRequest当前状态
- xmlhttp.status 属性服务器状态码,200:成功 404:未找到
readyState值 | 说明 |
---|
readyState=0 | 请求未初始化 |
readyState=1 | 服务器连接已建立 |
readyState=2 | 请求已被接收 |
readyState=3 | 请求正在处理 |
readyState=4 | 响应文本已被接收 |
@WebServlet("/content")
public class ContentServlet extends HttpServlet {
public ContentServlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter ().println ("<b>I'm a boy</b>");
}
}
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<input id="btnLoad" type="button" value="加载">
<div id="divContent"></div>
<script type="text/javascript">
document.getElementById("btnLoad").onclick=function () {
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
console.log(xmlhttp);
xmlhttp.open("GET","/content",true);
xmlhttp.send();
xmlhttp.onreadystatechange=function () {
if (xmlhttp.readyState==4&&xmlhttp.status==200){
var t = xmlhttp.responseText;
alert(t);
document.getElementById("divContent").innerHTML=t;
}
}
}
</script>
</body>
</html>
2.利用Ajax实现新闻列表
package com.imooc.ajax;
import com.alibaba.fastjson.JSON;
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.util.ArrayList;
import java.util.List;
@WebServlet("/news_list")
public class NewsListServlet extends HttpServlet {
public NewsListServlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List list=new ArrayList ();
list.add (new News ("TTOBE:2021年5月份","2021-5-1","TTOBE","..."));
list.add (new News ("TTOBE:2021年6月份","2021-6-1","TTOBE","..."));
list.add (new News ("TTOBE:2021年7月份","2021-7-1","TTOBE","..."));
list.add (new News ("TTOBE:2021年8月份","2021-8-1","TTOBE","..."));
String json = JSON.toJSONString (list);
System.out.println (json);
response.setContentType ("text/html;charset=UTF-8");
response.getWriter ().println (json);
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021060418364934.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUxNzQ2ODM5,size_16,color_FFFFFF,t_70)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="container">
</div>
<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/news_list",true);
xmlhttp.send();
xmlhttp.onreadystatechange=function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var text = xmlhttp.responseText;
console.log(text);
var json = JSON.parse(text);
console.log(json);
var html="";
for (var i = 0; i < json.length; i++) {
var news=json[i];
html=html+"<h1>"+news.title+"</h1>";
html=html+"<h2>"+news.date+" "+news.source+"</h2>";
html=html+"<hr/>"
}
document.getElementById("container").innerHTML=html;
}
}
</script>
</body>
</html>
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210604183708389.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUxNzQ2ODM5,size_16,color_FFFFFF,t_70)
开始好像没有太理解到,然后一直在地址栏输入news_list然后一直是json字符串,就以为没有转换成功。其实是通过JSON.toJSONString ()已经把数据转换成了json字符串,打印出来了。然后通过JSON.parse() 把json字符串转换成了js对象 显示在页面。
3.同步和异步
同步和异步
4.JQuery对Ajax的支持
- jQuery对Ajax进行了封装,提供了$.ajax()方法
- 语法:$.ajax(options)
常用设置项 | 说明 |
---|
url | 发送请求地址 |
type | 请求类型 get post |
data | 向服务器传递的参数 |
dataType | 服务器响应的数据类型 text json xml html jsonp script |
sucess | 接收响应时的处理函数 |
error | 请求失败时的处理函数 |
5.Ajax函数的使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function (){
$.ajax({
"url":"/news_list",
"type":"GET",
"data":"t=tiobe",
"dataType":"json",
"success":function (json) {
console.log(json)
for (var i = 0; i < json.length; i++) {
$("#container").append("<h1>"+json[i].title+"</h1>")
}
}
})
})
</script>
</head>
<body>
<div id="container"></div>
</body>
</html
5.二级联动菜单
@WebServlet("/channel")
public class ChannelServlet extends HttpServlet {
public ChannelServlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String level = request.getParameter ("level");
String parent = request.getParameter ("parent");
List chlist=new ArrayList ();
if (level.equals ("1")){
chlist.add (new Channel ("ai","前沿/区块链/人工智能"));
chlist.add (new Channel ("web","前端/小程序/JS"));
}else if(level.equals ("2")){
if (parent.equals ("ai")){
chlist.add (new Channel ("micor","微服务"));
chlist.add (new Channel ("blockchain","区块链"));
chlist.add (new Channel ("other","..."));
}else if(parent.equals ("web")){
chlist.add (new Channel ("html","HTML"));
chlist.add (new Channel ("css","CSS"));
chlist.add (new Channel ("other","...."));
}
}
String json = JSON.toJSONString (chlist);
response.setContentType ("text/html;charset=utf-8");
response.getWriter ().println (json);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-2.0.0.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
url:"/channel",
data:{"level":"1"},
type:"get",
dataType:"json",
success:function (json) {
console.log(json);
for (var i = 0; i < json.length; i++) {
var ch=json[i];
$("#lv1").append("<option value='"+ch.code+"'>"+ch.name+"</option>")
}
}
})
})
$(function () {
$("#lv1").on("change",function () {
var parent = $(this).val();
console.log(parent);
$.ajax({
url:"/channel",
data: {"level":"2","parent":parent},
dataType: "json",
type: "get",
success:function (json) {
$("#lv2>option").remove();
for (var i = 0; i < json.length; i++) {
var ch=json[i];
$("#lv2").append("<option value='"+ch.code+"'>"+ch.name+"</option>")
}
}
})
})
})
</script>
</head>
<body>
<select id="lv1" style="width: 200px;height: 30px">
<option selected="selected">请选择</option>
</select>
<select id="lv2" style="width: 200px;height: 30px"></select>
</body>
</html>
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210604205658463.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUxNzQ2ODM5,size_16,color_FFFFFF,t_70)