Java作为后端,接受前端传入的数据
1、后端控制器使用response返回数据到前端控制台
@Controller
@RequestMapping("/axios")
public class AxiosController {
@RequestMapping("/he")
public String hello(){
return "redirect:/axios.html";
}
@RequestMapping("/ajax")
public void ajax(HttpServletResponse response,@RequestBody String str) throws IOException {
System.out.println("数据:"+str);
PrintWriter writer = response.getWriter();
writer.write("hello Axios");
}
}
前端界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Axios</title>
<script rel="script" src="js/vue.min.js"></script>
<script rel="script" src="js/axios.min.js"></script>
</head>
<body>
<h1>Axios</h1>
<div id="vm">
{{message}}
<button @click="get">点击</button>
</div>
<script>
new Vue({
el:"#vm",
data:message="Tom",
methods:{
get:function () {
axios.post("/Demo/axios/ajax",{
one:"100",
two:"Hello"
})
.then(function (response) {
console.log(response.data);
})
}
}
});
</script>
</body>
</html>
2、后端返回json数据到前端页面
@RequestMapping("/he")
public String hello(){
return "redirect:/ajax.html";
}
@Autowired
StudentImpl student;
@RequestMapping("/ajaxs")
@ResponseBody
public Student ajaxs(Integer id){
System.out.println(id);
ArrayList<Student> students=student.getStudent(id);
System.out.println(students);
return students.get(1);
}
<body>
<h1>Axios</h1>
<div id="vm">
{{message}}
<h1 v-text="str"></h1>
<input type="text" v-model="ids">{{ids}}
<button @click="get">点击</button>
</div>
<script>
var m=new Vue({
el:"#vm",
data:{
message:"Tom",
str:"Hello",
ids:"填入数据"
},
methods:{
get:function () {
axios.get("/Demo/ajax/ajaxs",{
params:{id:m.ids}
})
.then(function (response) {
//错误this指向window,无法得到数据
m.str=response.data;
this.message=response.data;
console.log(response.data)
})
}
}
});
</script>
</body>
数据如下:
3、mounted挂载
可以在页面加载时就拿到数据
<body>
<h1>Axios</h1>
<div id="vm">
{{message}}
<h1 v-for="x in str">{{x.name}}</h1>
</div>
<script>
var m=new Vue({
el:"#vm",
data:{
message:"Tom",
str:"Hello"
},
mounted:function () {
axios.get("/Demo/mount/ajaxs?id=4",{
})
.then(function (response) {
//错误this指向window,无法得到数据
m.str=response.data;
console.log(response.data);
})
}
});
</script>
</body>