这似乎是一个经常被问到却很少被回答的问题。该文档有些含糊不清。
我想发布一组参数,如下所述。 网络服务:
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(@FormParam("param") String param){
// code..
}
javascript:
//var paramData = {"startDate":$("#startDate").val()};
var paramData = {startDate:$("#startDate").val()};
$.ajax({
type : 'POST',
url : 'mysite.com/post',
data: paramData,
contentType: 'application/x-www-form-urlencoded',
processData: false,
});
我已将 contentType 更改为 false,尝试序列化和字符串化参数数据等。参数在服务中以 null 形式出现,或者返回不受支持的媒体类型 HTTP 错误代码。
最佳答案
你做错了......
1. 默认情况下,您的 contentType
将为 application/x-www-form-urlencoded
,因此无需指定它.
2. 为什么使用processData: false
?您应该从这里阅读文档:
http://api.jquery.com/jQuery.ajax/
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
3. 由于 processData
默认情况下为 true
并且您不需要将其设置为 false
那么没有必要指定它。
4. 您只是传递一个 Object
作为 data
但您在哪里指定 param
因为这是你的方法使用的名称?看一下:public Response post(@FormParam("param") String param)
5. 由于您的 param
是 String
,因此您需要将 Object
转换为 >queryString
(与我们序列化表单相同),您可以使用 jQuery
轻松完成,您应该阅读以下内容:http://api.jquery.com/jquery.param/
6. 因此,最后您的代码必须如下所示:
var data = {
name: 'Oscar',
lastname: 'Jara'
};
$.ajax({
type: 'POST',
url: 'rest/service',
data: {
param: $.param(data)
}
});
7. 现在,如果您打印 REST
服务中的 param
变量包含的内容,您将得到以下结果:
name=Oscar&lastname=Jara
关于javascript - 将 FormParams 与 Jersey 和 jQuery 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217634/