2016-07-24 103 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"); 
    } 
});