Ajax学习笔记
Ajax学习笔记封面

Ajax学习笔记,前端基础,异步传参

[TOC]

Ajax

(asynchronous javascript and xml[异步请求 javascript xml])
异步的JavaScript和XML。

XMLHttpRequest对象

所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。
创建XMLHttpRequest对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
variable = new XMLHttpRequest();	//创建 XMLHttpRequest 对象
variable = new ActiveXObject("Microsoft.XMLHTTP"); //老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象


var xmlhttp;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

向服务器发送请求

方法 描述
open(method, url, async) 规定请求的类型、URL 以及是否异步处理请求。method:请求的类型;GET 或 POST。 url:文件在服务器上的位置。async:true(异步)或 false(同步)。
send(string) xhr对象调用了send方法,但没有响应。

关于post和get 的区别

以下使用post请求:

  • 无法使用缓存文件(更新服务器上的文件或数据库)
  • 向服务器发送大量数据(POST 没有数据量限制)
  • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

get请求

1
2
3
4
5
6
xmlhttp.open("GET","/try/ajax/demo_get.php",true);
xmlhttp.send();

//加入唯一随机id值作为区分
xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true);
xmlhttp.send();

post请求

1
2
3
4
5
6
7
xmlhttp.open("POST","/try/ajax/demo_post.php",true);
xmlhttp.send();

//send发送你说规定的数据
xmlhttp.open("POST","/try/ajax/demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
方法 描述
setRequestHeader(header,value) 向请求添加 HTTP 头。header: 规定头的名称。value: 规定头的、值。

传统请求

发起传统请求的方式

i.地址栏
ii.超级链接
iii.表单
iiii.javascript:location.href 函数

传统请求的问题

需要刷新页面才能等待结果进行后续操作。

异步请求

异步请求的特点

响应的内容不是新的页面,是一个页面的局部(字符串信息),所以用户在使用异步请求时,不需要等待响应,直接可以进行后续的操作

传统请求与异步请求的区别

响应内容

传统请求响应:新的页面 刷新页面
异步请求响应:页面的局部,字符串的信息

对于用户的操作

传统的请求:等待响应
异步的请求:不需要等待响应,用户可以直接进行后续操作

异步请求的开发

异步请求对象

javascript:XmlHttpRequest 对象 xhr
针对不同系列浏览器创建方式不同
Chrom|FF|safari

1
Var xhr = new XmlHttpRequest();

IE系

1
Var xhr = new ActionXObject(“Microsoft.XMLHTTP”);

xhr对象使用

i.创建xhr对象
ii.发送请求

1
xhr.open("get | post", url);

iii.如何传递数据

1
xhr.send(数据);

iiii.监听响应

1
xhr.readystate	//检测是否完成

状态码 状态
0 xhr对象被创建,并没有调用send()方法
1 xhr对象调用了send方法,但没有响应
2 xhr对象调用了send方法,响应已经返回客户端
3 响应解析
4 响应解析完成可以使用

xhr.status //响应是否正确

状态码 状态
404 xhr对象被创建,并没有调用send()方法
500 xhr对象调用了send方法,但没有响应
405 xhr对象调用了send方法,响应已经返回客户端
200 正确
1
2
3
4
5
6
xhr.onreadystatechange = function() {
if (xhr.readystate == 4 && xhr.status == 200) {
xhr.responseTest //获得响应文本
//Javascript中的DOM编程展示在页面中
}
}

用户名校验开发实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script type="text/javascript">
function test1() {
//获取用户名
var input = document.getElementById("username");
var username = input.value;
//发送AJAX请求
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//发送请求
xhr.open("GET", "${pageContext.request.contextPath}/check/checkusername1?username=" + username);
xhr.send(null);
//监听响应

xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
//获取校验结果
var message = xhr.responseText;
//DOM提示信息
var m = document.getElementById("message");
m.innerHTML = message;
}
}
}
</script>

1
2
3
4
5
6
7
8
9
<form action="">
用户名<input type="text" id="username" name="username" onblur="test1()" value="username">
<span id="message"></span>
<br />
密码<input type="password" name="password">
<br />
年龄<input type="text" name="age">
<br />
</form>

JSON协议串

本质

字符串

作用

在异构的编程体系中,进行数据的传输和交互

核心

对象形式

1
2
3
4
5
User {
id = 1;
userName = "hibiscidai";
age = 20;
}
1
{"id":1,"userName":"hibiscidai","age":18}

集合形式

数组:

1
String [] names = {"xiaoming", "xiaozhu", "xiaogou"}

1
["xiaoming","xiaozhu","xiaogou"]

含有对象的集合

1
List <User>
1
[{"id":1,"userName":"hibiscidai","age":18},	{"id":2,"userName":"xiaoming","age":20}]

内嵌对象

1
2
3
4
5
6
7
8
9
10
User {
id = 1;
userName = "hibiscidai";
Address address;
List<String> phone;
}
Address {
city = "zhengzhou";
street = "wenhualu";
}
1
{"id":1,"userName":"hibiscidai",{"city":"zhengzhou","street":"wenhualu"},["11111","2222","3333"]}

Map类型与对象的转换形式是一致的

1
2
3
Map<String, String> m = new HashMap<String, String>();
m.put("name1", "hibiscidai1");
m.put("name2", "hibiscidai2");
1
{"name2":"hibiscidai2","name1":"hibiscidai1"}

JSON协议串解析

异构体系中对象和集合与JSON串之间的转换
针对于java有jsonlib/gson(Google)/fastjson(ali)/jakenson(springmvc)
需要提前引入对应jar包

实际测试
用于本测试的对象
User.java | 省略setter和getter与构造方法

1
2
3
4
5
6
public class User {
public String name;
String phone;
public int age;
public Address address;
}

Address.java | 同User.java

1
2
3
4
public class Address {
public String city;
public String Street;
}

GSON(google)

java中的对象==》JSON串

1
2
3
4
5
6
7
8
9
@Test
// java中的对象==》JSON串
public void test1() {
User user = new User("hibiscidai", "123456", 18, null);

Gson gson = new Gson(); // 创建GSON对象
String string = gson.toJson(user);
System.out.println(string);
}
1
{"name":"hibiscidai","phone":"123456","age":18}

java中的集合==》JSON串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
// java中的集合==》JSON串
public void test2() {
User user1 = new User("hibiscidai1", "1234561", 181, null);
User user2 = new User("hibiscidai2", "1234562", 182, null);
User user3 = new User("hibiscidai3", "1234563", 183, null);

List<User> listUser = new ArrayList<User>(); // 创建List集合
listUser.add(user1);
listUser.add(user2);
listUser.add(user3);

Gson gson = new Gson(); // 创建GSON对象
String string = gson.toJson(listUser);
System.out.println(string);
}
1
[{"name":"hibiscidai1","phone":"1234561","age":181},{"name":"hibiscidai2","phone":"1234562","age":182},{"name":"hibiscidai3","phone":"1234563","age":183}]

java中的内嵌对象==》JSON

1
2
3
4
5
6
7
8
9
10
@Test
// java中的内嵌对象==》JSON
public void test3() {
Address addre = new Address("zhengzhou", "wenhualu");
User user = new User("hibiscidai1", "1234561", 181, addre);

Gson gson = new Gson(); // 创建GSON对象
String string = gson.toJson(user);
System.out.println(string);
}
1
{"name":"hibiscidai1","phone":"1234561","age":181,"address":{"city":"zhengzhou","Street":"wenhualu"}}

java中的Map对象==》JSON

1
2
3
4
5
6
7
8
9
10
11
@Test
// java中的Map对象==》JSON
public void test4() {
Map<String, String> maps = new HashMap<String, String>();
maps.put("1", "hibiscidai");
maps.put("2", "hibiscidai2");

Gson gson = new Gson(); // 创建GSON对象
String string = gson.toJson(maps);
System.out.println(string);
}
1
{"2":"hibiscidai2","1":"hibiscidai"}

JSON==》java中对象

1
2
3
4
5
6
7
8
9
10
11
@Test
// JSON==》java中对象
public void test5() {
User user = new User("hibiscidai", "123456", 18, null);

Gson gson = new Gson(); // 创建GSON对象
String string = gson.toJson(user);

User user2 = gson.fromJson(string, User.class); // json转对象
System.out.println(user2);
}
1
User [name=hibiscidai, phone=123456, age=18, address=null]

fastjson(ali)

对象>int>string

java中的对象==》JSON串

1
2
3
4
5
6
7
8
9
@Test
// java中的内嵌对象==》JSON
public void test3() {
Address addre = new Address("zhengzhou", "wenhualu");
User user = new User("hibiscidai1", "1234561", 181, addre);

String string = JSON.toJSONString(user);
System.out.println(string);
}
1
{"age":18,"name":"hibiscidai","phone":"123456"}

java中的集合==》JSON串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
// java中的集合==》JSON串
public void test2() {
User user1 = new User("hibiscidai1", "1234561", 181, null);
User user2 = new User("hibiscidai2", "1234562", 182, null);
User user3 = new User("hibiscidai3", "1234563", 183, null);

List<User> listUser = new ArrayList<User>(); // 创建List集合
listUser.add(user1);
listUser.add(user2);
listUser.add(user3);

String string = JSON.toJSONString(listUser);// 创建GSON对象
System.out.println(string);
}
1
[{"age":181,"name":"hibiscidai1","phone":"1234561"},{"age":182,"name":"hibiscidai2","phone":"1234562"},{"age":183,"name":"hibiscidai3","phone":"1234563"}]

java中的内嵌对象==》JSON

1
2
3
4
5
6
7
8
9
@Test
// java中的内嵌对象==》JSON
public void test3() {
Address addre = new Address("zhengzhou", "wenhualu");
User user = new User("hibiscidai1", "1234561", 181, addre);

String string = JSON.toJSONString(user);
System.out.println(string);
}
1
{"address":{"Street":"wenhualu","city":"zhengzhou","street":"wenhualu"},"age":181,"name":"hibiscidai1","phone":"1234561"}

java中的Map对象==》JSON

1
2
3
4
5
6
7
8
9
10
@Test
// java中的Map对象==》JSON
public void test4() {
Map<String, String> maps = new HashMap<String, String>();
maps.put("1", "hibiscidai");
maps.put("2", "hibiscidai2");

String string = JSON.toJSONString(maps);
System.out.println(string);
}
1
{"2":"hibiscidai2","1":"hibiscidai"}

JSON==》java中对象

1
2
3
4
5
6
7
8
9
10
11
@Test
// JSON==》java中对象
public void test5() {
User user = new User("hibiscidai", "123456", 18, null);

Gson gson = new Gson(); // 创建GSON对象
String string = gson.toJson(user);

User user2 = JSON.parseObject(string, User.class); // json转对象
System.out.println(user2);
}
1
User [name=hibiscidai, phone=123456, age=18, address=null]

DOM编程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<script type="text/javascript">
function test1() {
//创建异步请求对象
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//发送异步请求
//Struts2请求
xhr.open("GET", "${pageContext.request.contextPath}/user/selectAll");
xhr.send(null);
//监听响应
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
//把JSON串转化为JS数组
var users = JSON.parse(xhr.responseText);
//获取table标签对象
var table = document.getElementById("table");
for ( var i = 0; i < users.length; i++) {
//DOM编程
//创建行
var tr = document.createElement("tr");
//创建第一个单元格
var td = document.createElement("td");

//文本填充第一个单元格(列)
var id = document.createTextNode(users[i].id);
td.appendChild(id);//第一个单元格填充内容
tr.appendChild(td);//第一个单元行填充单元格

//第二个单元格(列)
var td1 = document.createElement("td");
var username = document.createTextNode(users[i].username);
td1.appendChild(username);
tr.appendChild(td1);

//第二个单元格(列)
var td2 = document.createElement("td");
var password = document.createTextNode(users[i].password);
td2.appendChild(password);
tr.appendChild(td2);

//将行列接入表格
table.appendChild(tr);
}
}
}
}
</script>

对于前台操作的表格

1
2
3
4
5
6
7
8
9
10
<body onload="test1()">
<table id="table" border="1px" cellspading="0px" cellpadding="0px"
width="80%">
<tr bgcolor="red">
<td>用户ID</td>
<td>用户名</td>
<td>密码</td>
</tr>
</table>
</body>

JSON转js对象或数组

(浏览器内置Jquery,Ext,vue,angluar js)浏览器内置对象,后续使用js框架

JSON.parse(jsonString)
—>js对象
—>ja数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function test1() {
/*
//定义JSON串
var u = '{"username":"hibiscidai","age":18}';
//吧json串转化为js对象
var user = JSON.parse(u);
alert(user.username);
alert(user.age);
*/
//定义JSON串
var s = '["hibiscidai","dai","mujin"]';
var ss = JSON.parse(s);
for (var i = 0; i < ss.length; i++) {
alert(ss[i]);
}
}

AJAX+Struts2+Mybatis整合

60204

案例:显示所有用户的信息

60405
selectAllAction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public String selectAll() {
// 调用业务
UserService us = new UserServiceImpl();
List<User> users = us.selectAllUsers();
// JSON串的转换
String jsonString = JSON.toJSONString(users);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.print(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
out.close();
return null;
}

前台表单

1
2
3
4
5
6
7
8
9
<body onload="test1()">
<table id="table" border="1px" cellspading="0px" cellpadding="0px" width="80%">
<tr bgcolor="red">
<td>用户ID</td>
<td>用户名</td>
<td>密码</td>
</tr>
</table>
</body>

Ajax函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<script type="text/javascript">
function test1() {
//创建异步请求对象
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//发送异步请求
xhr.open("GET", "${pageContext.request.contextPath}/user/selectAll");
xhr.send(null);
//监听响应
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
//把JSON串转化为JS数组
var users = JSON.parse(xhr.responseText);
//获取table标签对象
var table = document.getElementById("table");
for ( var i = 0; i < users.length; i++) {
//DOM编程
//创建行
var tr = document.createElement("tr");
//创建第一个单元格
var td = document.createElement("td");
//文本填充第一个单元格
var id = document.createTextNode(users[i].id);
td.appendChild(id);
tr.appendChild(td);

var td1 = document.createElement("td");

var username = document.createTextNode(users[i].username);
td1.appendChild(username);
tr.appendChild(td1);

var td2 = document.createElement("td");

var password = document.createTextNode(users[i].password);
td2.appendChild(password);
tr.appendChild(td2);

table.appendChild(tr);
}
}
}
}
</script>
文章作者: HibisciDai
文章链接: http://hibiscidai.com/2018/03/16/2018-03-16-Ajax学习笔记/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 HibisciDai
好用、实惠、稳定的梯子,点击这里