一.Axios异步框架
对原生的Ajax进行封装,简化书写。
给大家提供一下axios的源码:
链接:https://pan.baidu.com/s/1ZSrUBe0B4dIq7d6NpUzqOQ
提取码:gr86
将源码粘贴到项目之中。
1.基础使用
首先单独创建一个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;@WebServlet("/AxiosServlet")
public class Axios_Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String method =req.getMethod();System.out.println(method+"方法已启动~");String username= req.getParameter("username");System.out.println(username);resp.setContentType("text/html;charset=UTF-8");resp.getWriter().write("Axios启动~");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doGet(req, resp);}
}
引入外部js:
<script src="js/axios-0.18.0.js"></script>
如果是get方法,则参数直接写进Url:
axios({//大括号即为js对象method:"get",url:"http://localhost:8080/Ajax_S1_war/AxiosServlet?username=jsl"}).then(function (resp){alert(resp.data);})
如果是post方法,则把参数写进data域:
axios({//大括号即为js对象method:"post",url:"http://localhost:8080/Ajax_S1_war/AxiosServlet",data:"username=jsl"}).then(function (resp){alert(resp.data);})
2.别名方法
当然Axios内部可以直接调用get和post方法:
axios.get("http://localhost:8080/Ajax_S1_war/AxiosServlet?username=jsl").then(function (resp){alert(resp.data);})axios.post("http://localhost:8080/Ajax_S1_war/AxiosServlet","username=jsl").then(function (resp){alert(resp.data);})
均可启动成功:
二.Json数据格式
全名JavaScript Object Notation,即JS简谱、JS对象表示法。由于其语法简单,层次结构鲜明,现在多用于作为数据载体,在网络中进行数据传输。
1.基础语法
var jsl={"gender":"man","age":23,home:["拜仁","国米","阿贾克斯"]}alert(jsl.home[0]);
非常简单,不再赘述~
2.Java对象转换
- 请求数据:json字符串变为Java对象
- 响应数据:Java对象变为json字符串
采用阿里巴巴的API:Fastjson。
导入坐标:
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version>
</dependency>
创建一个用于测试的类:
public class TestDemo {private Integer id;private String username;private String password;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "TestDemo{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +'}';}
}
主方法中测试:
import com.alibaba.fastjson.JSON;public class Main {public static void main(String[] args) {//1.Java转换为JsonTestDemo TD=new TestDemo();TD.setId(1);TD.setPassword("123456");TD.setUsername("jsl");String jsonOb = JSON.toJSONString(TD);System.out.println(jsonOb);}
}
打印出json格式的数据:
然后是字符串转为java对象:
//2.json转为javaTestDemo t= JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}",TestDemo.class);System.out.println(t);