1.Axios发送普通的参数值给服务器端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>01.演示Axios发送普通的参数值给服务器端</title>
<script language="JavaScript" src="script/vue.js"></script>
<script language="JavaScript" src="script/axios.min.js"></script>
<script language="JavaScript">
window.onload=function(){
var vue = new Vue({
"el":"#div0",
data:{
uname:"lina",
pwd:"ok"
},
methods:{
axios01:function(){
axios({
method:"POST",
url:"axios01.do",
params:{
uname:vue.uname,
pwd:vue.pwd
}
})
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
});
}
}
});
}
</script>
</head>
<body>
<div id="div0">
uname:<input type="text" v-model="uname"/><br/>
pwd:<input type="text" v-model="pwd"/><br/>
<input type="button" @click="axios01" value="发送一个带普通请求参数值的异步请求"/>
</div>
</body>
</html>
@WebServlet("/axios01.do")
public class Axios01Servlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
System.out.println("uname = " + uname);
System.out.println("pwd = " + pwd);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(uname+"_"+pwd);
throw new NullPointerException("这里故意抛出一个空指针异常....");
}
}
2.Axios发送JSON格式的参数值给服务器端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>02.演示Axios发送JSON格式的参数值给服务器端</title>
<script language="JavaScript" src="script/vue.js"></script>
<script language="JavaScript" src="script/axios.min.js"></script>
<script language="JavaScript">
window.onload=function(){
var vue = new Vue({
"el":"#div0",
data:{
uname:"lina",
pwd:"ok"
},
methods:{
axios02:function(){
axios({
method:"POST",
url:"axios02.do",
data:{
uname:vue.uname,
pwd:vue.pwd
}
})
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
});
}
}
});
}
</script>
</head>
<body>
<div id="div0">
uname:<input type="text" v-model="uname"/><br/>
pwd:<input type="text" v-model="pwd"/><br/>
<input type="button" @click="axios02" value="发送JSON格式的参数值的异步请求"/>
</div>
</body>
</html>
@WebServlet("/axios02.do")
public class Axios02Servlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader bufferedReader = request.getReader();
String str = null ;
while((str=bufferedReader.readLine())!=null){
stringBuffer.append(str);
}
str = stringBuffer.toString() ;
//已知 String
//需要转化成 Java Object
Gson gson = new Gson();
//Gson有两个API
//1.fromJson(string,T) 将字符串转化成java object
//2.toJson(java Object) 将java object转化成json字符串,这样才能响应给客户端
User user = gson.fromJson(str, User.class);
response.getWriter().write(user);
}
}
3.JSON.toJSONString(java中Object类型数据可以是集合等等)