簡體   English   中英

Request Param中的Ajax POST數據

[英]Ajax POST data in Request Param

我正在發出一個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())。 一切正常。

謝謝你的幫助。

我剛剛用最新版本的spring boot和jquery做了一個小項目,它運行良好,根據調查我發現有2個因素可以解決這個問題,一個來自jquery,另一個來自Spring MVC轉換器:

1- jquery ajax有contentType參數

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

如果這個更改為application/json或者application/xml將改變它向服務器發送請求的方式然后會對服務器解析產生問題,但它是默認值將發送表單作為key=value coma分離,這對於FormHttpMessageConverter是可以的“這將我們帶到下一點”

2- spring MVC正在使用FormHttpMessageConverter進行"application/x-www-form-urlencoded"解析或轉換,如果此轉換器更改為其他轉換器,則可以使用@RequestParam

MappingJackson2HttpMessageConverter'application/json'

要么

'application/xml' Jaxb2CollectionHttpMessageConverter

所以它會期待另一個請求,你可以使用@RequestBody獲得它

因此,您必須使用瀏覽器中的開發工具檢查來自jquery的請求是form,json還是xml,然后檢查spring命令/配置以確保此請求由FormHttpMessageConverter轉換,此轉換器可以通過以下方式更改: @RequestMapping的參數。

你不能使用$ .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");
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM