Is there a way (In PHP) of detecting if the script

2019-07-15 12:41发布

问题:

I'd like a script that could detect if called by jquery

If not, it'd display the page+layout, if not, it'd just so the content (but that is irrelevant)

But yeah, a way of detecting if it was called by jquery load - ajax - or directly requested.

Cheers!

回答1:

Could you not send a GET parameter with the load?

Ie:

jquery=1 //(for load)

jquery=2 //(for the 'low-level' ajax call)

Any other value for normal script load

Then you let the PHP script deal with determining what to do next. By reading the value of $_GET['jquery']



回答2:

You might want to take a look at the HTTP headers your server is receiving.

For instance, let's consider I have this page :

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
</head>
<body>
    <div id="test"></div>
    <script type="text/javascript">
        $('#test').load('temp.php');
    </script>
</body>
</html>

And the temp.php script contains only this :

<?php
var_dump($_SERVER);

die;


When load is executed, the "test" <div> will contain the dump of $_SERVER ; and it'll include this, amongst other things :

'HTTP_X_REQUESTED_WITH' => string 'XMLHttpRequest' (length=14)

XMLHttpRequest is the object that's used to make Ajax request.


This means you should be able to detect if the request was made via an AJax query, with something like this :

if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
    && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    echo "Ajax";
} else {
    echo "Not Ajax";
}

With this, you can detect whether your page is called "normally", or via an Ajax request, and decide if you must include layout or not.


BTW : this is exactly the solution that's used by, for instance, Zend Framework, to detect Ajax requests.



回答3:

If I'm remembering correctly, jQuery's AJAX functions send a X-Requested-With header (with a value of XMLHttpRequest).



回答4:

if you're using Zend Framework you could use

// in one of your controllers
if ($this->getRequest()->isXmlHttpRequest()) {
  // ...
}

http://framework.zend.com/manual/en/zend.controller.request.html