1. 程式人生 > 其它 >ajax 提交form表單資料

ajax 提交form表單資料

一、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));
}
我從來不相信什麼懶洋洋的自由。我向往的自由是通過勤奮和努力實現的更廣闊的人生。 我要做一個自由又自律的人,靠勢必實現的決心認真地活著。