【发布时间】:2017-07-01 17:54:04
【问题描述】:
我想尝试使用 JQuery AJAX 将 JSON 数据发送到 JAX-RS Web 服务,但我遇到了问题。
我在 JAX-RS 上的方法使用 JSON 并生成 JSON,但是当我尝试发送 JSON 数据时,我的方法没有收到任何参数。我错过了什么?
这是我尝试过的
function callApi(counter){
var apiDat = {param1:counter};
$.ajax({
type: 'POST',
url: 'http://localhost:8080/xdbg/webresources/generic/value',
data: JSON.stringify(apiDat),
crossOrigin: true,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
success: function(data) {
console.log(data);
}
});
}
$(function () {
callApi(123);
});
请注意,我正在使用 CORS 进行方法调用:
@Path("generic")
public class GenericResource implements ContainerResponseFilter{
@Context
private UriInfo context;
@Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext cres) throws IOException {
cres.getHeaders().add("Access-Control-Allow-Origin", "*");
cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
cres.getHeaders().add("Access-Control-Max-Age", "1209600");
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/value")
public String GetValue(
@DefaultValue("") @QueryParam("param1") String param1
)throws Exception{
System.out.println("value = " + param1);
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", param1);
return outputJsonObj.toString();
}
这里是 JSON 格式:
{"output":"123"}
我错过了什么? 谢谢
【问题讨论】:
标签: javascript java jquery json web-services