How to detect an ajax request in the best possible way?
I'm currently using this in my controller:
private boolean isAjax(HttpServletRequest request){
String header = request.getHeader("x-requested-with");
if(header != null && header.equals("XMLHttpRequest"))
return true;
else
return false;
}
But I don't like this way, I think there should have a better solution with Spring.
That is the only "generic" way to detect an Ajax request.
But keep in mind: that's not failproof, it is just a best effort attempt, it is possible to make an Ajax request without sending the X-Requested-With
headers.
jQuery usually includes that header. Maybe another lib doesn't. The protocol certainly doesn't consider that header mandatory.
Just a note: Your code is perfectly valid, though you could write it a bit simpler:
private boolean isAjax(HttpServletRequest request) {
String requestedWithHeader = request.getHeader("X-Requested-With");
return "XMLHttpRequest".equals(requestedWithHeader);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With