这是一个Jersey数据服务,用于将数据发布到服务器并将其存储到数据库中:
@Path("/add")
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response create(Resource Resource) {
Response r = null;
String message = "sucessfully added";
try {
r = Response.status(200).entity(message).build();
ResourceDAO dao = new ResourceDAO();
dao.createResource(Resource);
} catch (SQLException e) {
message = "Exception in creating new Resource " + e;
r = Response.status(409).entity(message).build();
e.printStackTrace();
} catch (RuntimeException e) {
message = "Exception in creating new Resource " + e;
r = Response.status(409).entity(message).build();
e.printStackTrace();
} catch (Exception e) {
message = "Exception in creating new Resource " + e;
r = Response.status(409).entity(message).build();
e.printStackTrace();
}
return r;
}
以下是执行POST调用的AJAX客户端:
$.ajax({
type : "POST",
url : "rest/network/add",
contentType : 'application/json; charset=utf-8',
dataType : "json",
data : JSON.stringify(data),
success : function(msg /*what should be over here instead of msg if I am to receive a response from the server? */) {
//alert: displays the response that comes from the server
}
});
问题:Web服务必须将响应返回给ajax-client,而ajax-client必须在警报中显示响应。 如果遇到异常(数据库中已存在数据)的响应与没有异常时的响应不同。
问题:对服务器端和客户端代码进行了哪些更改,以便可以发送和接收响应?
非常感谢任何帮助。 感谢。
答案 0 :(得分:0)
你试过
吗?success : function(response) {
alert(response.responseText);
},
error : function(jqXHR, textStatus,errorThrown) {
//here you would print the errorThrown
}
答案 1 :(得分:0)
Web服务如下所示:
@Path("/add")
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response create(Resource resource) throws Exception {
Response r = null;
String message = null;
System.out.println("in post");
ResourceDAO dao = new ResourceDAO();
message = dao.createResource(resource);
/*this message as a function of createResource: success returns- "Created" exception returns = "Not Created"*/
r = Response.status(200).entity(message).build();
return r;
}
ajax调用如下所示:
$.ajax({
type : "POST",
url : "rest/Resource/add",
contentType : 'application/json; charset=utf-8',
dataType : "json",
data : JSON.stringify(data),
statusCode : {
200 : function(jqXHR) {
$.messager.alert('Request Status',
jqXHR.responseText);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$('#createResourceDialog').dialog('close');
$.messager.alert('Error',
'Unable to connect to the server');
}
});
此代码工作正常。但它执行
error : function(jqXHR, textStatus, errorThrown) {
$('#createResourceDialog').dialog('close');
$.messager.alert('Error',
'Unable to connect to the server');
}
每一次 - 甚至在执行statusCode块之后。这听起来不合逻辑。我希望只有当ajax调用无法与URL /服务器通信时才会执行错误块。需要帮助!