使用ajax提交数据的几种方式

本文深入解析了前后端交互中常见的几种参数传递方式,包括JSON.stringify形式的POST请求、普通的POST请求、@PathVariable路径变量和GET请求的具体实现。通过具体的代码示例,详细介绍了如何在前端使用jQuery的$.ajax方法发送不同类型的请求,并在后端使用SpringMVC框架的@Controller注解处理这些请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、JSON.stringify形式传参

js代码
$.ajax({
       url: Path + "/addOrgUpdate",
       //OrgSurvey.OrgSurveyData为一个对象
       data: JSON.stringify(OrgSurvey.OrgSurveyData),
       type: "post",
       contentType: "application/json", //必须有
       dataType: "json", //表示返回值类型,不必须
       success: function (data) {
           if (data.code === 0) {
               Aexit.success("信息保存成功!");
               location.replace(location);
               layer.closeAll('dialog');
               $("#button2").show();
               $("#button1").hide();
           } else {
               Aexit.error(data.message);
           }
       }
})
Controller代码
    @RequestMapping(value = "/addOrgUpdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxCommonObject add(@RequestBody OrgSurvey dto,
                                HttpSession session) {
            AjaxCommonObject ajaxCommonObject = new AjaxCommonObject();
    		、、、
    		、、、
    		、、、
    		return ajaxCommonObject;
    }

二、post请求方式提交

js代码
//提交信息
 $.ajax({
       url: Path + "/auditOrgInfo",
       data: {"orgId": orgId, 
       		  "result": result, 
       		  "failReason": failReason},
       type: "post",
       dataType: "json", //表示返回值类型,不必须
       success: function (data) {
           if (data.code === 0) {
               Aexit.success("审核通过!");
               window.parent.tableRefresh();
               window.parent.closeLayer();
           } else {
               Aexit.error("提交失败!" + data.message + "!");
           }
       }
   });
Controller代码
@RequestMapping(value = "auditOrgInfo")
@ResponseBody
 public AjaxCommonObject auditOrgInfo(@RequestParam(required = true) String orgId,
                                      @RequestParam(required = true) String result,
                                      @RequestParam(required = false) String failReason,
                                      HttpSession session) {
           AjaxCommonObject ajaxCommonObject = new AjaxCommonObject();
	       、、、
	       、、、
	       、、、
	       return ajaxCommonObject;
 }

三、@PathVariable用法

使用@PathVariable接收参数,参数值需要在url进行占位,前端传参的URL:

js代码
url = “${ctx}/edit/${Id}/${name}”
Controller代码
@RequestMapping("/edit/{id}/{name}")
public String edit(Model model, @PathVariable long id,@PathVariable String name) {       
    return page("edit");
}

前端传参的URL于后端@RequestMapping的URL必须相同且参数位置一一对应,否则前端会找不到后端地址

其他示例:
js代码:

    var CityGradeStatistic = {
        id: "CityGradeStatisticId"
    }
    CityGradeStatistic.initColumn = function () {
        return [       
            {title: '操作', field: 'operate', align: 'center', formatter: CityGradeStatistic.operatoion, width: '10%'}
        ];
    }
    
    //操作
    CityGradeStatistic.operatoion = function(value, row, index) {
        return '<button type="button"  "CityGradeStatistic.detail(\'' + row.evaluationDestId + '\',\'' + row.city + '\',\'' + row.grade + '\',\'' + row.gradeCount + '\',\'' + row.orgName + '\')" class="btn btn-xs btn-primary" ' +
            'style="margin-right:5px;"><i class="fa fa-search"></i>详情</button>';
    }
    
    //打开详情页
    CityGradeStatistic.detail = function(evaluationDestId,city,grade,gradeCount,orgName) {
        $('#evaluationDestId').val(evaluationDestId);
        var index = layer.open({
            type: 2,
            title: '验收单位扣分详情',
            content: Aexit.ctxPath + '/unite_grade/unite_grade_statistic_detail/' + city + '/' + grade + '/' + gradeCount + '/' + orgName,
            area: ['1000px', '500px'],
            maxmin: true
        });
        this.layerIndex = index;
        layer.full(index);
    }

controller代码:

    /**
     * 跳转到详情页
     */
    @RequestMapping("/unite_grade_statistic_detail/{city}/{grade}/{gradeCount}/{orgName}")
    public String uniteGradeStatisticDetail(@PathVariable String city,
                                             @PathVariable int grade,
                                             @PathVariable int gradeCount,
                                             @PathVariable String orgName,
                                             Model model) {
        model.addAttribute("city",city);
        model.addAttribute("grade",grade);
        model.addAttribute("gradeCount",gradeCount);
        model.addAttribute("orgName",orgName);
        return "statistics/unite_grade_statistic_detail";
    }

四、get请求方式

js代码:
 $.ajax({
        url: Path + "/final_file",
        type: "GET",
        cache: false,
        data: {
            serialNo: serialNo,
            orgId: orgId
        },
        dataType: "json", //表示返回值类型,不必须
        success: function (data) {
      			、、、
      			、、、
      			、、、
        }
    });
Controller代码:
@RequestMapping(value = "/final_file", method = RequestMethod.GET)
@ResponseBody
public AjaxCommonObject getDirectorFile(@RequestParam("serialNo") String serialNo,
                                        @RequestParam("orgId") Integer orgId) {
    AjaxCommonObject ajaxCommonObject = new AjaxCommonObject();
   		、、、
   		、、、
   		、、、
    return ajaxCommonObject;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值