Home >Backend Development >PHP Tutorial >ajax - php可以直接区分出form表单提交和xhr的post提交吗

ajax - php可以直接区分出form表单提交和xhr的post提交吗

WBOY
WBOYOriginal
2016-06-06 20:25:241351browse

RT。查了下很多资料里提到可以区分的前提都是前端手动添加一个x-requested-with字段到request header里去,但是原生的xhr里不带这个头的,所以想问下如果前端不配合的情况下,后台可以直接判断出来数据是form表单的submit提交还是利用ajax的post提交的吗?

回复内容:

RT。查了下很多资料里提到可以区分的前提都是前端手动添加一个x-requested-with字段到request header里去,但是原生的xhr里不带这个头的,所以想问下如果前端不配合的情况下,后台可以直接判断出来数据是form表单的submit提交还是利用ajax的post提交的吗?

并不能的,xhr也是执行了HTTP提交,默认情况的头都是一样的。不过如果你前端用的是JQ,那会加入x-requested-with的头的。

嗯 输出这个对比下 $_SERVER["HTTP_X_REQUESTED_WITH"]

<code>public function isAjax()
{
    if (!isset($_SERVER["HTTP_X_REQUESTED_WITH"])) {
        return false;
    }
    $http_x_request = $_SERVER["HTTP_X_REQUESTED_WITH"];
    if ( $http_x_request && strtoupper($http_x_request) == "XMLHTTPREQUEST") {
        return true;
    }
    return false;
}</code>

<code>/**
     * Returns true if the request is a XMLHttpRequest.
     *
     * It works if your JavaScript library sets an X-Requested-With HTTP header.
     * It is known to work with common JavaScript frameworks:
     *
     * @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
     *
     * @return bool true if the request is an XMLHttpRequest, false otherwise
     *
     * @api
     */
public function isXmlHttpRequest()
{
    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}</code>

laravel中AJAX的判断,不是标准头也是业内标准了。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn