您的位置:首页 > 编程语言 > Java开发

简单的springMVC+vue.js+axios实现

2017-03-08 10:43 597 查看
二、springMVC处理请求及向前台传json数组格式数据

@RequestMapping("getStudent")
public void getStudent(HttpServletRequest req,HttpServletResponse resp){
try {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String name=req.getParameter("name");
String sex=req.getParameter("sex");
byte[] b;
try {
b = name.getBytes("ISO-8859-1");
name=new String(b,"utf-8");
b = sex.getBytes("ISO-8859-1");
sex=new String(b,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}//用tomcat的格式(iso-8859-1)方式去读。

System.out.println("姓名:"+name+"\t性别:"+sex);
try {
PrintWriter out=resp.getWriter();
out.print("[{lattice:\"格子\"},{lattice:\"222\"}]");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


三、vue.js创建Vue对象

var vm=new Vue({
el:'#box',
data:{
myData:[
{
name:"格子",
sex:'男'
},{
name:'小芳',
sex:'女'
}],
username:'',
age:'',
nowIndex:-100
},
methods:{
add:function(){
this.myData.push({
name:this.username,
age:this.age
});

this.username='';
this.age='';
},
deleteMsg:function(n){
if(n==-2){
this.myData=[];
}else{
this.myData.splice(n,1);
}
},
submit:function(){
//使用vue推荐的axios进行前端与服务器数据交互
axios.get('<%=path%>/student/getStudent.do?lattice=lattice', {
params: vm.myData[1]//此处只能传json对象(已经构造完成的或者在此处构造json对象)
})
.then(function (response) {
console.log(response);
//回传的是一个json对象,包括data,status
//{data: "[{lattice:"格子"},{lattice:"222"}]", status: 200, statusText: "OK", headers: Object, config: Object…}

var json=eval(response.data);
$.each(json,function(){
console.log(this.lattice);
});

alert(response.data);
})
.catch(function (response) {
console.log(response);
});
/*//使用jquery ajax
$.ajax({
type: "POST",
url: "<%=path%>/student/getStudent.do",
data: "lattice=lattice",
dataType : "json",
success: function(msg){
// alert(msg);
//alert( "Data Saved: " + msg.login_username );
var jsons=eval(msg);
$.each(jsons,function(index,item){
alert(item.login_username);
});
}
});*/
}
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息