在 ThinkPHP 中使用原生 js 发起 Ajax 请求的时候、在控制器无法使用 IS_AJAX 进行判断。而使用 jQuery 中的 ajax 是没有问题的。
在ThinkPHP中、有一个判断是 ajax 请求的常量 IS_AJAX;
Ajax 请求常用的有两种情况:一种是原生 js 的 ajax 请求、一种是 jQuery 的 ajax 请求。
Accept: application/json, text/javascript, */*; q=0.01Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9Connection: keep-aliveContent-Length: 22Content-Type: application/x-www-form-urlencoded; charset=UTF-8Cookie: PHPSESSID=ns9mjve234erh0qerlcl180v52Host: localhostOrigin: http://localhostReferer: http://localhost/ok/User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/547.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/547.36X-Requested-With: XMLHttpRequest
Accept: */*Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9Connection: keep-aliveCookie: PHPSESSID=ns9mjve234erh0qerlcl180v52Host: localhostReferer: http://localhost/tp/User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/547.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/547.36
在 tp3.2.3 版本中
\ThinkPHP\Library\Think\App.class.php (Line:49)
define(‘IS_AJAX‘, ((isset($_SERVER[‘HTTP_X_REQUESTED_WITH‘]) && strtolower($_SERVER[‘HTTP_X_REQUESTED_WITH‘]) == ‘xmlhttprequest‘) || !empty($_POST[C(‘VAR_AJAX_SUBMIT‘)]) || !empty($_GET[C(‘VAR_AJAX_SUBMIT‘)])) ? true : false);
使用 jquery 发送 ajax 请求的时候、比使用原生 js 中的 ajax 多一个请求头 X-Requested-With: XMLHttpRequest。
而且 ThinkPHP 就是利用判读是否存在请求头这种原理去定义常量 IS_AJAX 的。
在发送ajax请求的时候设置一个对应的请求头信息。
function page( page ){ var ajax = new XMLHttpRequest() ajax.open( ‘get‘, ‘__URL__/show?page=‘+page, true ) ajax.setRequestHeader("X-Requested-With", "XMLHttpRequest"); ajax.send() ajax.onreadystatechange = function () { if ( ajax.readyState == 4 && ajax.status == 200 ) { document.getElementById( ‘box‘ ).innerHTML = ajax.responseText; } }}
设置完之后、再次看请求头信息、与之前的对比、多了一条
Accept: */*Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9Connection: keep-aliveCookie: PHPSESSID=ns9mjve234erh0qerlcl180v52Host: localhostReferer: http://localhost/tp/index.php/Home/Index/showUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/547.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/547.36X-Requested-With: XMLHttpRequest