欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ThinkPHP 中使用 IS_AJAX 判断原生 JS 中的 Ajax 出现问题

程序员文章站 2022-07-02 16:53:08
问题: 在 ThinkPHP 中使用原生 js 发起 Ajax 请求的时候、在控制器无法使用 IS_AJAX 进行判断。而使用 jQuery 中的 ajax 是没有问题的。 在ThinkPHP中、有一个判断是 ajax 请求的常量 IS_AJAX; Ajax 请求常用的有两种情况:一种是原生 js ......

问题:

在 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

如此问题便解决了。