ajax-Jquery

要导入Jquery.js的包,Jquery对ajax操作进行了封装,简化了ajax开发的流程.实现了多浏览器的兼容.

  • ajax函数

    函数名称: $.ajax

    参数列表: 长度为1,需要传递一个对象.

    通常传递到参数1的对象,我们使用JSON格式传输,属性与值描述如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    {
    url:"请求的地址",
    type:"请求方式GET/POST...",
    async:"默认true,表示异步请求",
    data:"请求的参数,格式与网址?后的格式一致",
    dataType:"TEXT/JSON",//表示服务器返回的数据类型.如果编写JSON , 我们接收到的数据 就是一个对象
    success:function(data){
    //当服务器请求成功时, 这里执行
    //参数data就是响应的内容.
    // 当dataType的值为TEXT时, data是一个string类型的数据
    // 当dataType的值为JSON时, data是一个对象.
    },
    error:function(){
    //当服务器返回的状态码不再200-299的范围 , 则表示失败, 这里执行
    }
    }

在html文件中输入

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
function x1(){
//1. 先得到要传递的两个参数, id和s1
var id = $("#id").val();
var s1 = $("#s1").val();
//2. 通过ajax , 将参数传递给s1.do
var index = layer.load();
$.ajax({
url:"s1.do",
type:"GET", //也可以写POST
data:"id="+id+"&s1="+s1,
dataType:"JSON",
success:function(data){
layer.close(index);
layer.msg(data.msg);
if(data.status == 1){
//服务器p图完成
var url = data.url;
$("#div1").html("<img src='"+url+"'>");
}
},
error:function(){
layer.close(index);
layer.msg("请检查网络...");
}
});
}

创建Putil.java,并输入

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class PUtil {
/* public static void main(String[] args) throws Exception {
String url = getJson(1, "厚程");
System.out.println(url);
}
*/
public static String getJson(int id,String text){
return getJson(id+"", text);
}
public static String getJson(String id,String text){
try {
text = URLEncoder.encode(text, "UTF-8");
//网址对象
URL url = new URL("http://itdage.cn/B/img?id="+id+"&s1="+text);
//打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//得到输入流
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
//得到机器人回复的内容
String json = br.readLine();
return json;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

创建Servlet文件,输入

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
import util.PUtil;
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;
/**
* Servlet implementation class Servlet1
*/
@WebServlet("/s1.do")
public class Servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.setContentType("text/html");
//设置编码为UTF-8
response.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
String s1 = request.getParameter("s1");
String url = null;
String json = null;
if(id==null || s1 == null) {
json = "{\"msg\":\"必须传递id与s1\",\"status\":-1}";
}else {
url = PUtil.getJson(id, s1);
json = "{\"url\":\""+url+"\",\"msg\":\"制图完成\",\"status\":1}";
}
response.getWriter().append(json);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
  • get函数与post函数

    两个函数的格式,完全一致,一个用于GET请求,一个用于POST请求.

    函数名称: $.get $.post

    参数列表:

    1
    2
    3
    4
    5
    列表长度为4:
    参数1. url : 请求地址
    参数2. data: 请求时携带的参数,与网址?后的参数格式一致.
    参数3. success: 当请求成功时,处理的函数
    参数4. 响应的数据类型: TEXT/JSON

    格式示例:

    1
    2
    3
    $.get("s1.do","",function(data){

    },"JSON");

在html文件中输入

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
</head>
<body>
<h3>快递查询</h3>
<input placeholder="请输入快递单号"><button onclick="x1()">查询</button>
<script type="text/javascript">
function x1(){
$("#ul1").html("");
//1. 得到用户输入的快递单号
var number = $("input").val();
//2. 发送ajax请求
layer.msg("拼命查询中...",{icon:16,shade:0.01});
$.get("s2.do","number="+number,function(data){ //也可以写成$.post()
if(data.status == 0){
//查询成功
var arr = data.result.list;
for(var i=0;i<arr.length;i++){
var $li = $("<li>时间:"+arr[i].time+"<br>进度:"+arr[i].status+"</li>");
$("#ul1").append($li);
}
}else{
//查询失败
layer.msg("很遗憾, 查询失败了");
}
},"JSON");
}
</script>
<ul id="ul1">
</ul>
</body>
</html>

创建FindExpressUtil.java,并输入

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
52
53
54
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FindExpressUtil {
public static void main(String[] args) throws Exception {
String json = find("9978875206496");
System.out.println(json);
}
/**
所有快递公司请求示例:
https://itdage.cn/kd/exnames.do
根据单号查询公司请求示例:
https://itdage.cn/kd/findexname.do?number=123456
快递查询请求示例:
https://itdage.cn/kd/find.do?number=123456&exname=shunfeng
* @param number
* @return
*/
public static String find(String number){
try {
//1. 准备网址
// URL url = new URL("https://itdage.cn/kd/find.do?number="+number);
URL url = new URL("https://api.jisuapi.com/express/query?appkey=5701500bf5e5e1df&type=auto&number="+number);
//2. 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3. 得到网络连接的输入流
//(其实下载 就是复制文件 , 只不过复制的源文件从FileInputStream 更改为了网络连接的输入流)
InputStream is = conn.getInputStream();
//4. 将字节输入流, 按照UTF-8转换为字符输入流
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
//5. 为了方便读取, 将字符输入流, 转换为缓冲字符输入流
BufferedReader br = new BufferedReader(isr);
//6. 准备一个变长字符串, 存储读取的所有内容
StringBuffer sb = new StringBuffer();
//7. 准备一个字符串, 存储每次读取的一行内容
String text = null;
while((text = br.readLine())!=null) {
sb.append(text);
}
return sb.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

创建Servlet文件,输入

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
import util.FindExpressUtil;
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;
/**
* Servlet implementation class Servlet2
*/
@WebServlet("/s2.do")
public class Servlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
String number = request.getParameter("number");
String json = null;
if(number!=null && !number.equals("")) {
json = FindExpressUtil.find(number);
}else {
json = "{\"status\":-1,\"msg\":\"查询失败 , 请传递正确的单号\"}";
}
response.getWriter().append(json);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
  • getJSON函数

    .get.get、.post相比只是少了参数返回值type

    函数名称: $.getJSON

    参数列表:

    1
    2
    3
    4
    参数列表长度为3
    参数1. url : 请求地址
    参数2. data: 请求时携带的参数, 与网页?后的参数格式一致
    参数3. success: 当请求成功时, 处理的函数.
    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
    <h3>快递查询2</h3>
    <input placeholder="请输入快递单号"><button onclick="x1()">查询</button>
    <script type="text/javascript">
    function x1(){
    $("#ul1").html("");
    //1. 得到用户输入的快递单号
    var number = $("input").val();
    //2. 发送ajax请求
    layer.msg("拼命查询中...",{icon:16,shade:0.01});
    $.getJSON("s2.do","number="+number,function(data){
    if(data.status == 0){
    //查询成功
    var arr = data.result.list;
    for(var i=0;i<arr.length;i++){
    var $li = $("<li>时间:"+arr[i].time+"<br>进度:"+arr[i].status+"</li>");
    $("#ul1").append($li);
    }
    }else{
    //查询失败
    layer.msg("很遗憾, 查询失败了");
    }
    });
    }
    </script>
    <ul id="ul1">

    </ul>
  • load函数

    与其他的ajax函数不同,它是使用jquery对象调用的.

    功能:利用ajax发送一个url请求,将返回结果填充到$obj元素中(常用于页面引入)

    函数名称: $obj.load

    参数列表:

    1
    2
    3
    4
    参数列表长度为3
    参数1. url: 请求地址
    参数2. [data]: 传递的参数
    参数3. [success]: 请求成功时的处理函数.

在html文件中输入

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
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
</head>
<body>
<h3>JD商品</h3>
<script type="text/javascript">
//表示当前页数
var count = 1;
function x1(i){
if(count==1 && i==-1){
layer.msg("已经是第一页了");
return;
}
count+=i;
//发起ajax, 请求页面.得到新的商品内容
$("#content").load("page.jsp","count="+count);
//也可以把url写成上述servlet映射的网址,返回的JSon可以直接返回到标签$("#content")下
$("#count").html(count);
}
</script>
<div>
<button onclick="x1(-1)">上一页</button>
<span id="count">1</span>
<button onclick="x1(1)">下一页</button>
</div>
<div id="content">
<div class="item">
商品1 ,图片请自行脑补
</div>
<div class="item">
商品2 ,图片请自行脑补
</div>
<div class="item">
商品3 ,图片请自行脑补
</div>
<div class="item">
商品4 ,图片请自行脑补
</div>
</div>
</body>

创建page.js文件,输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String countString = request.getParameter("count");
int count = Integer.parseInt(countString);

int startNum = (count-1)*10+1;
for(int i=0;i<10;i++){
%>
<div class="item">
商品<%=startNum %> ,图片请自行脑补
</div>
<%
startNum++;
}
%>

ajax-Vue

除了需要引入vue.js文件以外,还需要引入:vue-resource.js

创建WeatherUtil.java,并输入

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class WeatherUtil {
public static void main(String[] args) {
String json = getJson("沈阳");
System.out.println(json);
}
public static String getJson(String city){
try {
city = URLEncoder.encode(city,"UTF-8");
//网址对象
URL url = new URL("https://api.jisuapi.com/weather/query?appkey=5701500bf5e5e1df&city="+city);
//打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//得到输入流
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
//得到机器人回复的内容
String json = br.readLine();
return json;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

创建Servlet文件,输入

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
import util.WeatherUtil;
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;

/**
* Servlet implementation class Servlet3
*/
@WebServlet("/s3.do")
public class Servlet3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
String city = request.getParameter("city");
String json = WeatherUtil.getJson(city);
response.getWriter().append(json);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
  • 基于全局的Ajax

    GET请求格式:

    Vue.http.get(“请求地址”,[传递的参数]).then(success,error);

    在html文件中输入

    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
    <h3>天气查询</h3>
    <input id="input1" placeholder="请输入查询的城市"><button onclick="x1()">查询</button>
    <div id="div1"></div>
    <script type="text/javascript">
    function x1(){
    var div1 = document.getElementById("div1");
    div1.innerHTML = "";
    var city = document.getElementById("input1").value;
    //s3.do?city=输入框内容
    Vue.http.get("s3.do",{params:{"city":city}}).then(function(res){
    var date = res.body.result.date;
    var week = res.body.result.week;
    var weather = res.body.result.weather;
    var temp = res.body.result.temp;
    var templow = res.body.result.templow;
    var temphigh = res.body.result.temphigh;
    div1.innerHTML =
    "日期:"+date+"&nbsp;&nbsp;&nbsp;"+week+"<br><br>"
    +"天气情况:"+weather
    +"<br>当前温度:"+temp+"<br>"
    +"今天温度区间: "+templow+" ~ "+temphigh;
    ;

    },function(res){
    div1.innerHTML = "很遗憾, 查询失败";
    });
    }
    </script>

    POST请求格式:

    Vue.http.post(“请求地址”,[传递的参数],{“emulateJSON”:true}).then(success,error);

    在html文件中输入

    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
    <h3>天气查询</h3>
    <input id="input1" placeholder="请输入查询的城市"><button onclick="x1()">查询</button>
    <div id="div1"></div>
    <script type="text/javascript">
    function x1(){
    var div1 = document.getElementById("div1");
    div1.innerHTML = "";
    var city = document.getElementById("input1").value;
    //s3.do?city=输入框内容
    Vue.http.post("s3.do",{"city":city},{"emulateJSON":true}).then(function(res){
    var date = res.body.result.date;
    var week = res.body.result.week;
    var weather = res.body.result.weather;
    var temp = res.body.result.temp;
    var templow = res.body.result.templow;
    var temphigh = res.body.result.temphigh;
    div1.innerHTML =
    "日期:"+date+"&nbsp;&nbsp;&nbsp;"+week+"<br><br>"
    +"天气情况:"+weather
    +"<br>当前温度:"+temp+"<br>"
    +"今天温度区间: "+templow+" ~ "+temphigh;
    ;

    },function(res){
    div1.innerHTML = "很遗憾, 查询失败";
    });
    }
    </script>
  • 在Vue实例中使用的ajax

    GET请求格式:

    this.$http.get(“请求地址”,[传递的参数]).then(success,error);

    GET请求参数传递的格式{params:{键1:值1,键2:值2…键n:值n}}

    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
    <h3>天气查询</h3>
    <div id="main">
    <input id="input1" placeholder="请输入查询的城市" v-model="city"><button @click="x1">查询</button>
    <div><br><br>
    日期:{{time}}&nbsp;&nbsp;&nbsp;&nbsp;{{week}}<br><br>
    天气:{{weather}}<br>
    当前温度:{{temp}}<br>
    当天温度区间:{{templow}} ~ {{temphigh}}<br>
    </div>

    </div>
    <script type="text/javascript">
    var vue = new Vue({
    el:"#main",
    data:{
    city:"",
    time:"",
    week:"",
    weather:"",
    temp:"",
    templow:"",
    temphigh:"",
    },
    methods:{
    x1:function(){
    this.$http.get("s3.do",{params:{"city":this.city}}).then(function(res){
    this.time = res.body.result.date;
    this.week = res.body.result.week;
    this.weather = res.body.result.weather;
    this.temp = res.body.result.temp;
    this.templow = res.body.result.templow;
    this.temphigh = res.body.result.temphigh;
    },function(res){

    });
    }
    }
    });
    </script>

    POST请求格式:

    this.$http.post(“请求地址”,[传递的参数],{“emulateJSON”:true}).then(success,error);

    POST请求参数传递的格式{键1:值1,键2:值2…键n:值n}

    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
    <h3>天气查询</h3>
    <div id="main">
    <input id="input1" placeholder="请输入查询的城市" v-model="city"><button @click="x1">查询</button>
    <div><br><br>
    日期:{{time}}&nbsp;&nbsp;&nbsp;&nbsp;{{week}}<br><br>
    天气:{{weather}}<br>
    当前温度:{{temp}}<br>
    当天温度区间:{{templow}} ~ {{temphigh}}<br>
    </div>

    </div>
    <script type="text/javascript">
    var vue = new Vue({
    el:"#main",
    data:{
    city:"",
    time:"",
    week:"",
    weather:"",
    temp:"",
    templow:"",
    temphigh:"",
    },
    methods:{
    x1:function(){
    this.$http.post("s3.do",{"city":this.city},{"emulateJSON":true}).then(function(res){
    this.time = res.body.result.date;
    this.week = res.body.result.week;
    this.weather = res.body.result.weather;
    this.temp = res.body.result.temp;
    this.templow = res.body.result.templow;
    this.temphigh = res.body.result.temphigh;
    },function(res){

    });
    }
    }
    });
    </script>

success函数与error函数:

这两个函数都存在一个参数:response,指的是响应对象.

响应对象的属性:

1.url : 请求的网址
2.body: 服务器返回的响应体,如果是JSON格式,则body为对象,如果不是JSON格式,则body为string
3.ok : boolean值,如果响应码为200-299之间值为true,表示成功.
4.status: 服务器响应的状态码,例如:200,404,500 ...
5.statusText: 响应状态码对应的文字,例如status==200时,则statusText=ok.

响应对象的函数:

1.text() : 以字符串形式, 返回响应体.
2.json() : 以对象形式, 返回响应体.
3.blob() : 以二进制Blob对象形式, 返回相应内容