问题:
在 ThinkPHP 中使用原生 js 发起 Ajax 请求的时候、在控制器无法使用 IS_AJAX 进行判断。而使用 jQuery 中的 ajax 是没有问题的。
在ThinkPHP中、有一个判断是 ajax 请求的常量 IS_AJAX; Ajax 请求常用的有两种情况:一种是原生 js 的 ajax 请求、一种是 jQuery 的 ajax 请求。
分析:
先看看使用 jQuery 中使用 ajax 发送请求的时候的头信息:
Accept: application/json, text/javascript, /; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Content-Length: 22
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: PHPSESSID=ns9mjve234erh0qerlcl180v52
Host: localhost
Origin: http://localhost
Referer: 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.36
X-Requested-With: XMLHttpRequest
再看看使用 JS 中的原生 ajax 发送请求的时候的头信息:
Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Cookie: PHPSESSID=ns9mjve234erh0qerlcl180v52
Host: localhost
Referer: 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
再查看在TP是如何定义的常量 IS_AJAX:
在 tp3.2.3 版本中
\ThinkPHP\Library\Think\App.class.php (Line:49)
define(‘IS_AJAX’, ((isset(KaTeX parse error: Double subscript at position 16: _SERVER['HTTP_X_̲REQUESTED_WITH'…_SERVER[‘HTTP_X_REQUESTED_WITH’]) == ‘xmlhttprequest’) || !empty(
P
O
S
T
[
C
(
′
V
A
R
A
J
A
X
S
U
B
M
I
T
′
)
]
)
∣
∣
!
e
m
p
t
y
(
_POST[C('VAR_AJAX_SUBMIT')]) || !empty(
POST[C(′VARAJAXSUBMIT′)])∣∣!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, br
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Cookie: PHPSESSID=ns9mjve234erh0qerlcl180v52
Host: localhost
Referer: http://localhost/tp/index.php/Home/Index/show
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
X-Requested-With: XMLHttpRequest
如此问题便解决了。
文章来自:https://www.itjmd.com/news/show-5344.html
PHP中开源框架ThinkPHP巧妙利用 IS_AJAX判断JS 中 Ajax 存在问题
最新推荐文章于 2021-04-25 21:11:00 发布