使用jQuery与后端进行数据传输代码示例
目录
使用jQuery与后端进行数据传输代码示例
1.编写前端页面 + Ajax请求
- 表单域 form (三大部分:form、表单域、提交按钮 type=“submit”。 每个input需要有名字!否则无法被serialize()添加进数据中)
- 为submit添加on监听事件。1.阻止默认行为 2.通过 form选择器.serialize( )把表单的所有数据添加进data中(务必每个input都有个name属性)
- 通过jquery发送ajax请求!规定好url、type、method、data、success等等
- 特别注意:若后端返回的是 @ResponseBody String 则 type=”text“ ; 若后端返回的是json,则type=”JSON“
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.4.1.js"></script>
<script>
$(function(){
$('form').on('submit',function(e){
//Step1.阻止submit的默认行为
e.preventDefault();
//Step2.获取表单内所有的数据【各个input 一定要有name属性!】
var str = $('form').serialize();
//Step3.发送Ajax请求
$.ajax({
url: "http://localhost:9090/test", //后端地址
type: "text", //提交方式
method: "GET",
data: str,
dataType: "text", //规定请求成功后返回的数据
success: function (data) {
//请求成功之后进入该方法,data为成功后返回的数据
console.log(data);
console.log("发送ajax成功");
},
error: function (errorMsg) {
console.log(errorMsg);
console.log("发送ajax失败");
}
});
})
})
</script>
</head>
<body>
<form>
<input type="text" name="name" value="" placeholder="name">
<input type="text" name="age" value="" placeholder="age">
<button type="submit">submit</button>
</form>
</body>
</html>
2.编写后端响应(只说明数据交换部分。详细知识点请看后端的SpringMVC、Springboot 等笔记)
- 首先,需要解决跨域问题。 在Controller类上添加一个 @CrossOrigin 即可解决跨域问题
- 添加 @RequestMapping() 作为前端ajax 发送url的地址
- @ResponseBody 让返回的String为text类型 / 让返回的对象自动转为json类型
- Controller内的方法,需要使用 对象 作为参数,接收来自前端的参数
package com.example.module1.controller;
import com.example.module1.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@CrossOrigin
public class TestController {
@RequestMapping("/test")
@ResponseBody
public String test(User user){
System.out.println(user);
return "success";
}
}