PHP中開源框架ThinkPHP巧妙利用 IS_AJAX判斷JS 中 Ajax 存在問題

PHP中開源框架ThinkPHP巧妙利用 IS_AJAX判斷JS 中 Ajax 存在問題

問題:

  在 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($_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, 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章