javascript 如何区分 Ajax 请求和普通 Http 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4885893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to differentiate Ajax requests from normal Http requests?
提问by R K
I am using JSF framework in my application. I need to run a specific script before the render response phase in my Phase Listener class.
我在我的应用程序中使用 JSF 框架。我需要在 Phase Listener 类中的渲染响应阶段之前运行特定脚本。
Condition for running this script is that, if the request triggered is a Ajax request i need to run the script, if the request triggered is a Http request i should not run that script.
运行此脚本的条件是,如果触发的请求是 Ajax 请求,我需要运行该脚本,如果触发的请求是 Http 请求,我不应该运行该脚本。
Can anyone please help me to differentiate the requests recieved.?
谁能帮我区分收到的请求。?
回答by BalusC
Ajax requests have usually a X-Requested-With: XMLHttpRequestrequest header. In JSF, you can obtain the request headers by ExternalContext#getRequestHeaderMap().
Ajax 请求通常有一个X-Requested-With: XMLHttpRequest请求头。在 JSF 中,您可以通过ExternalContext#getRequestHeaderMap().
ExternalContext externalContext = facesContext.getExternalContext();
Map<String, String> headers = externalContext.getRequestHeaderMap();
boolean ajax = "XMLHttpRequest".equals(headers.get("X-Requested-With"));
回答by Tatu Ulmanen
Ajax requests set a server variable X-Requested-Withto XMLHttpRequest. You can use that information to differentiate between ajax and normal requests.
Ajax 请求将服务器变量设置X-Requested-With为XMLHttpRequest. 您可以使用该信息来区分 ajax 和普通请求。
回答by eirirlar
private boolean isAjaxRequest() {
PartialViewContext partialViewContext = FacesContext.getCurrentInstance().getPartialViewContext();
return null != partialViewContext && partialViewContext.isAjaxRequest();
}

