问题描述
如何以最佳方式检测ajax请求?
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;
}
但是我不喜欢这种方式,我认为Spring应该有更好的解决方案.
But I don't like this way, I think there should have a better solution with Spring.
推荐答案
这是检测Ajax请求的唯一通用"方法.
That is the only "generic" way to detect an Ajax request.
但是请记住:这不是故障预防,这只是尽力而为的尝试,可以在不发送 X-Requested-With 标头
.
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通常包含该标头.也许另一个库没有.该协议当然不认为该标头是必需的.
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);
}
这篇关于Spring MVC检测到Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!