前端Ajax傳遞Json資料,後端處理兩種方式

來源:互聯網
上載者:User

標籤:比較   message   rip   ons   int   post   url   bsp   tty   

在這裡只討論在前端通過Ajax遠程傳輸Json資料的,不討論通過form的形式傳遞資料

第一種方式:

  前端傳遞過來的資料剛好和我們的bean實體物件屬性一致,則可以使用對象的形式接受。

前端寫法:
 1  $().ready(function(){ 2       var obj = JSON.stringify({‘userNo‘:‘121589‘,‘processId‘:‘15‘,‘processName‘:‘測試審批‘,‘description‘:‘這是一個測試‘}); 3       alert(obj); 4                 5       //後台使用對象的形式接受 6       $.ajax({ 7            url: "testJsonOne", 8            type: "post", 9            data: obj,10            contentType: ‘application/json;charset=utf-8‘,11            success : function(data){12                 alert("haha");13            }14        }); 15                16  });

特別要注意的點:

  1. contentType: ‘application/json;charset=utf-8‘ ,指定資料是以Json的形式傳遞

  2.要傳遞的data,要是一個Json格式的字串,最好先建立一個json對象,然後使用JSON.stringify()來轉換成字串形式

後台寫法:
//對象形式接受前端資料    @RequestMapping(value= "/testJsonOne",method = RequestMethod.POST)    @ResponseBody    public String testJson(@RequestBody PoMessageVo poMessageVo) {        System.out.println(poMessageVo.toString());        return "success";    }

注意點:

  1.前端資料和bean對象屬性要一致

  2.會使用到@RequestBody註解,而這個註解要先匯入jar包的,分別是jackson-core-asl-xxx.jar和jackson-mapper-asl-xxx.jar兩個包

  3.註解用法不瞭解的話,百度一下

 

第二種方式:

  有可能前端傳遞過來的資料很多很複雜,則我們可以在後端使用字串的形式接受,具體的處理,我們在後端自己再處理。

前端寫法:
//後台使用字串的形式接受的$.ajax({    url: "testJsonTwo",    type: "post",    //data: {jsonStr:‘nihao‘},    data: {jsonStr:obj},    //data: obj,    //contentType: ‘application/json;charset=utf-8‘,    success : function(data){        alert("haha");    }});

注意與上面的做比較:

  1. jsonStr指定後台只能以這個名稱接受
  2. Ajax上不用指定contentType: ‘application/json;charset=utf-8‘
後台寫法:
//以字串的形式接受前端資料@RequestMapping(value= "/testJson",method = RequestMethod.POST)@ResponseBodypublic String testJson(String jsonStr) {    System.out.println(jsonStr);        //這裡可以使用JsonMapper來處理jsonStr,比如轉成需要的bean對象    return "success";}

 

前端Ajax傳遞Json資料,後端處理兩種方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.