通过ajax传数据到后台,前端传json数据到后台,传FormData表单数据到后台

59 篇文章 1 订阅
1 篇文章 0 订阅

ajax的contentType :
1、ajax默认的contentType 为:contentType : “application/x-www-form-urlencoded”,使用场景是发送字符串。
2、contentType : ‘application/json;charset=UTF-8’,使用场景是后台不是接收单个字符串,而是一个实体类时就用它;或者是发送json数据。

一、前端传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;
}

三、传字符串数据到后台

js代码:

var textInfo= $("#divId").text();
$.ajax({
	url : '../../before/text/getInfo',
	contentType : "application/x-www-form-urlencoded",// 关键是加上这一行,指定类型
	data : {
		"textInfo" : textInfo
	},
	type : 'POST',
	async : false,
	success : function(res) {
		//TODO 渲染数据到页面
	}
});

后台控制类java代码:

	@RequestMapping(value = "/getInfo", method = RequestMethod.POST)
	@ResponseBody
	public String getInfo(HttpServletRequest request) {
		String textInfo= request.getParameter("textInfo");
		//业务需求 TODO
		return null;
	}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,在React中,你需要使用 `axios` 或者 `fetch` 等库来发起 AJAX 请求。 1. 安装 `axios` 库 在终端中运行以下命令来安装 `axios` 库: ``` npm install axios ``` 2. 发起 AJAX 请求 在 React 组件中,你可以在表单提交时发起 AJAX 请求。例如: ```jsx import React, { useState } from 'react'; import axios from 'axios'; function Form() { const [formData, setFormData] = useState({ name: '', email: '', message: '' }); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios.post('/api/contact', formData); console.log(response.data); } catch (err) { console.error(err); } } const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); } return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="name">Name:</label> <input type="text" name="name" id="name" value={formData.name} onChange={handleChange} /> </div> <div> <label htmlFor="email">Email:</label> <input type="email" name="email" id="email" value={formData.email} onChange={handleChange} /> </div> <div> <label htmlFor="message">Message:</label> <textarea name="message" id="message" value={formData.message} onChange={handleChange}></textarea> </div> <button type="submit">Submit</button> </form> ); } export default Form; ``` 这里我们定义了一个表单组件,其中包含 `name`,`email` 和 `message` 三个表单项。在 `handleSubmit` 函数中,我们使用 `axios.post` 发起 POST 请求,将表单数据作为请求体递给后端 `/api/contact` 接口。如果请求成功,我们在控制台中打印服务器返回的数据。 3. 处理后端请求 在后端中,你需要使用一个路由处理 POST 请求,并将表单数据存储到数据库中。例如,如果你使用 Node.js 和 Express 构建后端,可以使用以下代码: ```javascript const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.post('/api/contact', (req, res) => { const { name, email, message } = req.body; // 这里可以连接数据库,将表单数据存储到数据库中 // ... res.status(200).json({ success: true }); }); app.listen(3000, () => console.log('Server is running on port 3000')); ``` 这里我们使用 `body-parser` 中间件来解析请求体中的 JSON 数据。在 `/api/contact` 路由中,我们从请求体中获取表单数据,并将其存储到数据库中。如果存储成功,我们返回一个包含 `success: true` 的 JSON 响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值