How to find out if a request is an ajax request?

后端 未结 3 935
我在风中等你
我在风中等你 2021-02-11 02:41

I try to find out if a request to a PHP file is sent by ajax or not.

I googled it and read a whole a bunch of articles that suggest following method:

相关标签:
3条回答
  • 2021-02-11 03:15

    Not all browsers will send that response I usually use

    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {//Do stuff }
    

    and for ajax

    request = $.ajax({
        url: SomePage.php,
        type: "POST",
        data: {key: value}
    });
    request.done(function(returnedData) {
        //do done stuff
    });
    request.fail(function(jqXHR, textStatus) {
        //do fail stuff
    });
    

    Note:

    $HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. 
    (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that 
    PHP handles them as such). Also note that long arrays were removed since PHP 5.4.0 so 
    $HTTP_SERVER_VARS doesn't exist anymore.
    

    So var_dump($HTTP_SERVER_VARS); to see if its contained in there, also note that the $_SERVER is filled in by the webserver

    0 讨论(0)
  • 2021-02-11 03:15

    what you can do is provide your own defined variable, and use a command design pattern to test the outcome for instance:

    $.ajax({
       url: 'http://URL/test.php',
       data: {action: "ajax_request"},
       complete: function(res) {
       console.log(res.responseText);
     }
     });
    

    and the php test:

    if (isset($_POST['action']) && !empty($_POST['action'])) {
        $action = $_POST['action'];
        switch ($action) {
             case 'ajax_request' : echo 'This is an ajax request!';
            break;
    
       }
    }
    else
      echo 'This is not an ajax request!';
    

    try this also

     while(true)
     {
         ......
        if (window.XMLHttpRequest){
           echo 'This is an ajax request!';
           return new XMLHttpRequest();
        }
         else if(window.ActiveXObject)// for internet explorer
        {
             echo 'This is an ajax request'!;
             return new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
           echo 'This is not an ajax request!';
     }
    
    0 讨论(0)
  • 2021-02-11 03:21

    There's no 100% way to detect if the request was made via ajax. Even if someone sends header with "X-Requested-With: XMLHttpRequest" you shouldn't rely on it.

    0 讨论(0)
提交回复
热议问题