通过ajax传数据到后台,前端传json数据到后台,传FormData表单数据到后台
程序员文章站
2022-06-13 21:04:22
...
一、前端传json数据到后台
js代码:
var listText = [];
listText.push("value1");
listText.push("value2");
listText.push("value3");
$.ajax({
type : 'POST',
url : '../../before/text/getList',// TODO 发送请求到后台
// headers:{'Content-Type':'application/json;charset=UTF-8'},
contentType : 'application/json;charset=UTF-8',
dataType : 'json',
async : false,
data : JSON.stringify({
"listText" : listText
}),
success : function(res) {
if (res.code == 200) {
// TODO 渲染数据到页面
}
}
});
后台控制类java代码:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = BeforeTextController.BASE_URL)
public class BeforeTextController{
private static Logger logger = LoggerFactory.getLogger(BeforeTextController.class);
public static final String BASE_URL = "/before/text";
@RequestMapping(value = "/getList", method = RequestMethod.POST)
@ResponseBody
public String getList(HttpServletRequest request, @RequestBody JSONObject listJsonData) {
JSONArray listText= listJsonData.getJSONArray("listText");
Map<String, Object> map = new HashMap<>();
List list = new ArrayList<>();
for (int i = 0; i < listText.size(); i++) {
String listValue= (String) listText.get(i);
}
return null;
}
}
二、传FormData表单数据到后台
js代码:
var formData = new FormData();
formData.append("textValue1", "textValue1");//key value
formData.append("textValue2", "textValue2");
formData.append("textValue2", "textValue3");
$.ajax({
type : 'POST',
url : '../../before/text/getTypeList',// 发送请求到后台
async : false,
data : formData,
processData : false,
contentType : false,
success : function(res) {
//TODO 渲染数据到页面
}
});
后台控制类java代码:
@RequestMapping(value = "/getTypeList", method = RequestMethod.POST)
@ResponseBody
public ResponseDTO getTypeList(HttpServletRequest request) {
String textValue1= request.getParameter("textValue1");
String textValue2= request.getParameter("textValue2");
String textValue3= request.getParameter("textValue3");
//TODO 业务需求
return null;
}
下一篇: 记录一次JQuery表单效验