1. 程式人生 > >ThinkPHP 中使用 IS_AJAX 判斷原生 JS 中的 Ajax 出現問題

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

如此問題便解決了。