ajax示例


1、ajax以form形式发送数据

1.1 ajax代码

这里的contentType值是application/x-www-form-urlencoded,是默认的,不写也可以

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript">
	$(function() {
		$("button").click(function() {

			// 真正作为请求体发送给服务器的数据。
			// 在我们像提交表单一样发送数据时,不把JSON对象转换为JSON字符串
			var requestBody = {
				"empId" : 999,
				"empName" : "harry",
				"empSalary" : 128.56
			};

			$.ajax({
				"url" : "ajax/send/form/data", // 请求的目标地址
				"type" : "post", // 请求方式
				"data" : requestBody, // 请求体数据
				"contentType" : "application/x-www-form-urlencoded", //默认值,可以省略该项
				"dataType" : "json", // 服务器端返回数据的解析方式
				"success" : function(response) { // 服务器处理请求成功,执行这个函数,响应体从参数这里传入

					// response已经解析为JSON对象,可以直接使用“.属性名”方式访问具体属性
					var result = response.result;

					// 如果返回结果成功,显示成功(逻辑成功)
					if ("SUCCESS" == result) {
						alert("SUCCESS");
					}

					// 如果返回结果失败,显示消息(逻辑失败)
					if ("FAILED" == result) {

						var message = response.message;

						alert(message);
					}

				},

				"error" : function(response) { // 处理请求失败,例如:404、500、400等等

					alert(response);

				}
			});
		});
	});
</script>
</head>
<body>

	<button>点我发送数据(像提交表单一样)</button>

</body>
</html>

1.2 后端代码

	//因为前端传送的数据都是Employee这个对象对的属性,所以直接用对象接收
	//如果传送的是单个数据,使用@RequestParam("empName")String empName取值,直接用就可以了
	@ResponseBody
	@RequestMapping("/ajax/send/form/data")
	public ResultEntity<String> receiveFormData(Employee employee) {
		
		System.out.println(employee);
		
		//ResultEntity就是一个实体类,存了返回的的状态和消息提示
		return ResultEntity.successWithoutData();
	}

在这里插入图片描述

2、ajax以JSON形式发送数据

2.1 ajax代码

contentType的值和form形式不一致,这里是json格式的
"contentType":"application/json;charset=UTF-8"

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript">
	
	$(function(){
		$("button").click(function(){
			
			// Ajax请求的请求体如果是JSON格式,那么需要先将数据封装为JSON对象
			var jsonObj = [
				{
					"empId":666,
					"empName":"jerry",
					"empSalary":123.321
				},
				{
					"empId":555,
					"empName":"bob",
					"empSalary":456.654
				},
				{
					"empId":444,
					"empName":"kate",
					"empSalary":666.666
				}
			];
			
			// 将JSON对象转换为JSON字符串
			var requestBody = JSON.stringify(jsonObj);
			
			// 发送Ajax请求
			$.ajax({
				"url":"ajax/send/json/data",	// 请求的目标地址
				"type":"post",					// 请求方式
				"data":requestBody,				// 请求体数据
				"contentType":"application/json;charset=UTF-8",	//非默认值,不能省略
				"dataType":"json",				// 服务器端返回数据的解析方式
				"success":function(response) {			// 服务器处理请求成功,执行这个函数,响应体从参数这里传入
					
					// response已经解析为JSON对象,可以直接使用“.属性名”方式访问具体属性
					var result = response.result;
				
					// 如果返回结果成功,显示成功(逻辑成功)
					if("SUCCESS" == result) {
						alert("SUCCESS");
					}
					
					// 如果返回结果失败,显示消息(逻辑失败)
					if("FAILED" == result) {
						
						var message = response.message;
						
						alert(message);
					}
					
				}, 
				
				"error":function(response){			// 处理请求失败,例如:404、500、400等等
					
					alert(response);
					
				}
			});
			
		});
	});
	
</script>
</head>
<body>

	<button>JSON格式提交数据</button>

</body>
</html>

2.2 后端代码

  这里和以form形式的接收数据不一样,form形式的直接接收就可以,但是以json发送的,这里要用@RequestBody接收,不然接收的值是null,
  因为ajax传入的是集合,所以这里用的List接收的,传入的如果不是List,直接用对象或属性名接收就可以

	@ResponseBody
	@RequestMapping("/ajax/send/json/data")
	public ResultEntity<String> receiveJsonData(@RequestBody List<Employee> empList) {
		
		for (Employee employee : empList) {
			System.out.println(employee);
		}
		
		return ResultEntity.successWithoutData();
	}

3、ajax以form形式发送list数据

3.1 ajax代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript">
	
	$(function(){
		$("button").click(function(){
			
			// Ajax请求的请求体如果是JSON格式,那么需要先将数据封装为JSON对象
			var jsonObj = {
				"empList[0].empId":666,
				"empList[0].empName":"jerry",
				"empList[0].empSalary":123.321,
				"empList[1].empId":555,
				"empList[1].empName":"bob",
				"empList[1].empSalary":456.654,
				"empList[2].empId":444,
				"empList[2].empName":"kate",
				"empList[2].empSalary":666.666
			};
			
			// 发送Ajax请求
			$.ajax({
				"url":"ajax/send/form/list/data",	// 请求的目标地址
				"type":"post",					// 请求方式
				"data":jsonObj,				// 请求体数据
				"contentType":"application/x-www-form-urlencoded",	//非默认值,不能省略
				"dataType":"json",				// 服务器端返回数据的解析方式
				"success":function(response) {			// 服务器处理请求成功,执行这个函数,响应体从参数这里传入
					
					// response已经解析为JSON对象,可以直接使用“.属性名”方式访问具体属性
					var result = response.result;
				
					// 如果返回结果成功,显示成功(逻辑成功)
					if("SUCCESS" == result) {
						alert("SUCCESS");
					}
					
					// 如果返回结果失败,显示消息(逻辑失败)
					if("FAILED" == result) {
						
						var message = response.message;
						
						alert(message);
					}
					
				}, 
				
				"error":function(response){			// 处理请求失败,例如:404、500、400等等
					
					alert(response);
					
				}
			});
			
		});
	});
	
</script>
</head>
<body>

	<button>以表单形式提交List数据</button>

</body>
</html>

在这里插入图片描述

3.2 后端代码

package com.wzw.crowd.funding.ajax.entity;

import java.util.List;

public class EmployeeParam {
	
	private List<Employee> empList;
	
	public EmployeeParam() {
		// TODO Auto-generated constructor stub
	}

	public EmployeeParam(List<Employee> empList) {
		super();
		this.empList = empList;
	}

	@Override
	public String toString() {
		return "EmployeeParam [empList=" + empList + "]";
	}

	public List<Employee> getEmpList() {
		return empList;
	}

	public void setEmpList(List<Employee> empList) {
		this.empList = empList;
	}

}

这里是用form形式提交的,所以也不用@RequestBody

	@ResponseBody
	@RequestMapping("/ajax/send/form/list/data")
	public ResultEntity<String> receiveFormListData(EmployeeParam employeeParam) {
		
		List<Employee> empList = employeeParam.getEmpList();
		
		for (Employee employee : empList) {
			System.out.println(employee);
		}
		
		return ResultEntity.successWithoutData();
	}

在这里插入图片描述

4、ajax发送数组

4.1 ajax代码

traditional: true——这个重要的,不加的话,发送的时候会给你的参数再加个[],就报错了;

	var pathFile=["123","456"];
       $.ajax({
            async : false,
            cache : false,
            traditional: true,
            type : 'POST',
            data : {
                pathFile:pathFile
            },
            url : "acc/downFile",// 请求的路径
            error : function() {// 请求失败处理函数
            },
            success : function(data) {

            }
        });

4.2 后端代码

    @RequestMapping(params = "downFile")
    @ResponseBody
    public String downFile(HttpServletRequest request, String[] pathFile) {
        String[] pathFiles = pathFile;
        System.out.println(pathFile);
        return "123";
    }

5、ajax下载文件

ajax是弹不出文件下载框的,用以下替代方式

        var url = "/down/downFile";
        var fileName = "123.rar";
        var form = $("<form></form>").attr("action", url).attr("method", "post");
        form.append($("<input></input>").attr("type", "hidden").attr("name", "fileName").attr("value", fileName));
        form.appendTo('body').submit().remove();

6、FormData提交数据

<!DOCTYPE html>
<html>
<head>
  <title>文件上传示例</title>
</head>
<body>
  <input type="file" id="fileInput">
  <button onclick="uploadFile()">上传文件</button>
</body>
</html>
var fileInput= $('#fileInput')[0];
var zipFile= fileInput.files[0];	//通过id获取文件
//初始化一个空的表单
var fromData=new FromData();

// 获取页面已有的一个form表单
//var form = document.getElementById("myForm");
// 用表单来初始化
//var formData = new FormData(form);

//添加文件
formData.append("zipFile",zipFile);	
//添加数据
formData.append("username", "username");

在这里插入图片描述
在这里插入图片描述

小结

  一般情况下,使用第一种第二种就可以,第三种有点多余
┐(゚~゚)┌

中文乱码

contentType:application/x-www-form-urlencoded;charset=UTF-8

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值