x-requested-with 请求头 区分ajax请求还是普通请求

x-requested-with请求头区分ajax请求还是普通请求

在服务器端判断request来自Ajax请求(异步)还是传统请求(同步):

两种请求在请求的Header不同,Ajax异步请求比传统的同步请求多了一个头参数

1、传统同步请求参数

 accepttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

 accept-charsetgb2312,utf-8;q=0.7,*;q=0.7

 accept-encodinggzip,deflate

 accept-languagezh-cn,zh;q=0.5

 cache-controlmax-age=0

 connectionkeep-alive

 cookieJSESSIONID=1A3BED3F593EA9747C9FDA16D309AF6B

 host192.168.101.72:8080

 keep-alive300

 refererXXX

 user-agentMozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.9.0.15)Gecko/2009101601Firefox/3.0.15(.NETCLR3.5.30729)

2、Ajax异步请求方式

 accept*/*

 accept-languagezh-cn

 refererxxx

 x-requested-withXMLHttpRequest//表明是AJax异步

 content-typeapplication/x-www-form-urlencoded,text/JavaScript

 accept-encodinggzip,deflate

 user-agentMozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;Trident/4.0;QQDownload598;.NETCLR2.0.50727;.NETCLR3.0.04506.648;.NETCLR3.5.21022;CIBA;.NETCLR1.1.4322;.NETCLR3.0.4506.2152;.NETCLR3.5.30729;InfoPath.1)

 host192.168.101.72:8080

 content-length233

 connectionKeep-Alive

 cache-controlno-cache

 cookieCSS=undefined;JSESSIONID=1B9AC25036290F7FB6823CCE1A24E541

可以看到Ajax请求多了个x-requested-with,可以利用它,request.getHeader("x-requested-with");为null,则为传统同步请求,为XMLHttpRequest,则为Ajax异步请求。

相关推荐