后端与前端Ajax交互

12 篇文章 0 订阅
3 篇文章 0 订阅
接口方法统一用@ResponseBody处理返回json数据

如果单传一个String类型,dataType 用 text ; 传对象和集合用 json ;

Ajax给外部赋值 需要设置 async:false, 

填坑:必须注明[],有的地方会接收不到,后端接收数组 @RequestParam("ids[]") List<String> ids 

一、多部分文件上传

(@RequestParam(value = "files",required = false) MultipartFile[] files,@RequestParam(value = "id",required = false) Integer id)


    @PostMapping("editWorkExperience")
    public int editWorkExperience(@RequestParam Map<String, Object> params, HttpServletRequest request){
        WorkExperience workExperience = JSON.parseObject(JSON.toJSONString(params), WorkExperience.class);
        MultipartFile file = ((MultipartHttpServletRequest)request).getFile("dimissioCertificate");

 表单:

<form id="ff" method="post"  enctype="multipart/form-data">
        <input type="file" name="files"/>
        <input type="file" name="files"/>
</form>

Ajax方法:


              var formData = new FormData($('#ff')[0]);//新建一个表单数据
              formData.set('id',1) ;//可以添加发送的参数
              jQuery.support.cors=true;
              $.ajax({
               type: 'POST',
               dataType: 'json',
               url: '', 
               data: formData,//使用封装表单
               cache: false,  
               xhrFields: {
                withCredentials: true
               },
               crossDomain: true,
               contentType: false,  //这个需要关闭
               processData: false,  
               success: function (data) {
                  
               },
               error : function() {
                   console.log("异常!");
               }
           });

二、@RequestParam接收Ajax方式

(@RequestParam(value = "id",required = false) Integer id)

Ajax方法:

			jQuery.support.cors=true;
			$.ajax({
				type: 'POST',
				dataType: 'json',
				url: 'http://localhost:8080/getOnline',
				data: {},
				xhrFields: {
					withCredentials: true
				},
				crossDomain: true,
				contentType: 'application/x-www-form-urlencoded;charset=utf-8',
				success: function (data) {
				
				},
				error : function() {
					console.log('异常!');
				}
			});

三、@RequestBody接收Ajax方式

(@RequestBody People people)

People.java 自定义实体类

public class People extends BaseEntity{
    private Integer peopleId;
    private String peopleName;
......

Ajax方法:


              jQuery.support.cors=true;
              $.ajax({
               type: 'POST',
               dataType: 'json',
               url: '', 
               data: {'peopleId':1,'peopleName':'p1'},
               xhrFields: {
                withCredentials: true
               },
               crossDomain: true,
               contentType: 'application/json;charset=utf-8',  //json格式
               success: function (data) {

               },
               error : function() {
                   console.log("异常!");
               }
           });

四、新增一种写法JSON.stringify(data)

    @PostMapping("addDepartment")
    @ResponseBody
    public Object addDepartment(@RequestBody Department department){
        Tools.logger.info("进入getAllFDepartments");
        System.out.println(department.toString());
        Tools.logger.info("离开getAllFDepartments");
        return null;
    }

    //或者

    @PostMapping("addDepartment")
    @ResponseBody
    public Object addDepartment(String deptName){

        return null;
    }
            jQuery.support.cors=true;
            $.ajax({
                type: "POST",
                dataType: "json",
                url: ctx+'/findDepartmentByName',
                data:JSON.stringify(data.field),
                cache: false,
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                contentType: "application/json",
                success: function (data) {

                },
                error : function() {
                    console.log('异常!');
                }
            });

工具:

/**
 * ajax封装
 * @param ctx
 * @param url
 * @param data
 * @param successFunction
 * @param type
 */
function ykAjax(ctx,url,data,successFunction,type) {
    jQuery.support.cors=true;
    if(type==1||type=="1"){
        //单个数据提交,@RequestParam接收
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ctx+'/'+url,
            data: data,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/x-www-form-urlencoded;charset=utf-8',
            success: successFunction,
            error : function() {
                console.log('ajaxError!');
            }
        });
    }else if(type==2||type=="2"){
        //实体类接收@RequestBody
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ctx+'/'+url,
            data: data,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json;charset=utf-8',  //json格式
            success: successFunction,
            error : function() {
                console.log('ajaxError!');
            }
        });
    }else if(type==3||type=="3"){
        //表单提交;@RequestParam接收
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ctx+'/'+url,
            data: data,
            cache: false,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: false,  //这个需要关闭
            processData: false,
            success: successFunction,
            error : function() {
                console.log('ajaxError!');
            }
        });
    }else if(type==4||type=="4"){
        //layui的表单提交@RequestBody或不写
        $.ajax({
            type: "POST",
            dataType: "json",
            url: ctx+'/'+url,
            data: data,
            cache: false,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: "application/json",
            success: successFunction,
            error : function() {
                console.log('ajaxError!');
            }
        });
    }else {
        console.log('AjaxTypeError!')
    }
}

实体类中属性list集合接收方式

@Data
public class Information implements Serializable {
    private String userName;
    private List<Experience> experiences;
}
<input name="experiences[0].name">

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值