欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用Ajax向网页表单提交数据的方法

最编程 2024-07-20 20:26:41
...

一、ajax传输非json;

$("form").serialize(),序列话表单结果:

此时不用设置contentType(定义的是发送至服务器的数据类型,data-Type定义的是服务器返回的数据),后端接收参数不需要@Requestbody

$.ajax({
    type: 'post',
    url: 'your url',
    data: $("form").serialize(),
    success: function(data) {
        // your code
    }
});

后端代码:

@RequestMapping("/testStr")
@ResponseBody
public R testStr(TestEntity entity){
return R.of(service.testCreate(entity));
}

二、ajax传输json

serializeJSON(),自定义的函数;把序列号的form数据 转成json格式

var json =  $("form").serializeJSON();
$.ajax({
    type: 'post',
    url: 'your url',
    data: JSON.stringify(json),//必须是字符串
    contentType:"applicantion/json",
    success: function(data) {
        // your code
    }
});

后端代码

@RequestMapping("/testStr")
@ResponseBody
public R testStr(@RestBody TestEntity entity){
return R.of(service.testCreate(entity));
}

推荐阅读