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

后端 未结 3 934
我在风中等你
我在风中等你 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

    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!';
     }
    

提交回复
热议问题