2016-07-24 100 views
3

阿賈克斯POST數據我想提出一個POST請求如下:在請求帕拉姆

$.ajax({ 
    url :"/clientCredentials.json", 
    type: "POST", 
    data: { 
     "clientEmail": email, 
     "clientName":clientName, 
     "orgName":orgName, 
     "logoURL":logoURL, 
     "redirectURI":redirectUri 
    }, 
    success: function(response){ 
     alert("sucess"); 

    }, 
    error:function(response){ 
     alert("something went wrong"); 
    } 
}); 

在服務器上,我使用@RequestParams得到這個數據。

@RequestParam String clientEmail, @RequestParam String clientName, @RequestParam String orgName, @RequestParam String logoURL, @RequestParam String redirectURI 

我從服務器獲取如下:

{"code":"400","errorMessage":"Required String parameter 'clientEmail' is not present"} 

如果我使用@RequestBody而不是@RequestParam接受這個數據其工作的罰款。

我的問題是如何在請求參數中獲取這些數據?我究竟做錯了什麼? 我也試過jquery($。get(),$ .post())。沒有工作。

感謝您的任何幫助。

+0

你可以在你的瀏覽器開發工具中看到它。在Chrome上,這是在網絡選項卡下。 我不能幫你關於spring和@RequestParams,但jQuery。 – Loenix

+0

謝謝,@Loenix。我知道了。有些東西在我的服務器配置中是錯誤的。 – Suraj

回答

3

我只是做小項目,彈簧引導和jQuery和它運作良好,的最新版本,並根據調查中,我做了,我發現有兩個因素可以使這個問題,一個來自jQuery和其他一個Spring MVC的轉換器:

1- jQuery的阿賈克斯的contentType參數

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') 

,如果這一個改變application/jsonapplication/xml會改變它發送請求到服務器,然後將問題向服務器p的方式arsing,但它是默認值將發送形式key=value昏迷分離,這是確定與FormHttpMessageConverter「這是促使我們下一個點」

2 - Spring MVC的使用FormHttpMessageConverter"application/x-www-form-urlencoded"解析或轉換,那麼你可以使用@RequestParam如果該轉換器改變爲其它轉換器,如:

MappingJackson2HttpMessageConverter'application/json'

Jaxb2CollectionHttpMessageConverter'application/xml'

所以它會期待着另一個請求,則可以使用@RequestBody

所以得到的,你有你的瀏覽器中使用的開發工具,以檢查要求從jQuery的會是它的形式,JSON或XML,然後檢查你春天代碼/配置以確保該請求被FormHttpMessageConverter轉換,該轉換器可以通過@RequestMapping的參數進行更改。

2

你不能使用帶有效載荷(數據)的$ .get,但你可以使用$ .post。請在您的請求參數中添加屬性contentType

$.ajax({ 
    url :"/clientCredentials.json", 
    type: "POST", 
    contentType: "application/json", 
    data: { 
     "clientEmail": email, 
     "clientName":clientName, 
     "orgName":orgName, 
     "logoURL":logoURL, 
     "redirectURI":redirectUri 
    }, 
    success: function(response){ 
     alert("sucess"); 
    }, 
    error:function(response){ 
     alert("something went wrong"); 
    } 
});