For example i have java class post:
public class Post{
String title;
String text;
}
If i create an instance of this class and convert it into ajax response in my servlet controller
@RestController
public class AjaxNewsController {
@JsonView(Views.Public.class)
@PostMapping(value = "/getPost")
public AjaxResponseBody getSearchResultViaAjax(@RequestBody AjaxPostResponse postId) {
AjaxResponseBody result = new AjaxResponseBody();
result.setCode("200");
result.setMsg("found POST");
result.setResult(post);
return result;
}
}
My question is: can i retrieve post fields title and text with javascript on a client side and if i can then how?
Here is an example of console with my response in browse console
but how can i extract my post with fields in ajax and jquery?
UPD
after some reaserach i found that somehow my serlvet doesn't convert my java pojo into json. How should i do it?
UPD2
my request sends normaly but serlvet doesn't convert POST class into json.
here is my javascript :
function likePost(postId,ratingElem, ratingChange) {
var search = {}
search["postId"] = postId;
search["rating"] = ratingChange;
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "likePost",
data : JSON.stringify(search),
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
changeRating(ratingElem,data.post.getTopic());
},
error : function(e) {
console.log("ERROR: ", e);
changeRating(ratingElem,'error');
},
done : function(e) {
console.log("DONE");
enableSearchButton(true);
}
});
}
status and message is fine but result is empty.
try it:
var req = new XMLHttpRequest();
req.open('POST', 'your_url', false);
req.send(null);
if(req.status == 200)
dump(req.responseText);
and if you want to get data from another domain please read cors
So i solved my problem. I use com.fasterxml.jackson.core so i just need to mark fields in my class that i want to convert into json with @JsonView annotation like
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "post_id",
unique = true, nullable = false)
@JsonView(Views.Public.class)
private Integer postId;
Everything that marked will be converted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.