如何在PHP中判断一个网页请求是ajax请求还是普通请求?你可以通过传递参数的方法来 实现,例如使用如下网址请求: /path/to/pkphp.com/script.php?ajax 在PHP脚本中使用如下方法判断: if(isset($_GET['ajax'])) { …这是一个ajax请求,然后… } else { …这
如何在PHP中判断一个网页请求是ajax请求还是普通请求?你可以通过传递参数的方法来 实现,例如使用如下网址请求:
<font face="NSimsun">/path/to/pkphp.com/script.php?ajax</font>
在PHP脚本中使用如下方法判断:
<font face="NSimsun">if(isset($_GET['ajax'])) {<br>…这是一个ajax请求,然后…<br>}<br>else {<br>…这不是一个ajax请求,然后…<br>}</font>
通过传递_GET参数的方法简单实现了网页请求的判断。但是如果需要这样的功能,这个 方法可能就有弊端,功能需求如下:
1.通过ajax请求的网页与普通请求的网页内容是不相同的;
2.通过ajax请求的网页是为了方便用户操作,两种方法请求打开的网页必须的内容是相 同的,只是ajax请求到的网页内容比较简化和使用,去除了网页的大框架模板;
3.这么做的目的是:用户在网页操作时通过ajax实现,而搜索引擎访问网页时(相当于 普通打开网页),得到的内容是一个完整的网页(包含了网页的大框架模板)。
要完成上面的这个功能,就不能使用前面介绍的通过GET参数传递来判断了,如果使用 GET传递来判断的话,用户ajax请求和普通网页请求都会是一样的内容,因为你不可能为一 个链接设置一个带ajax判断参数和不带的URL。那么如何才能实现这个功能呢?必须通过服 务器端PHP判断解决这个问题。也就是今天要说的PHP如何判断ajax请求。这个问题要解决有 一个先决条件,那就是你使用的ajax框架必须是jquery。在jquery框架中,对于通过它的 $.ajax, $.get, or $.post方法请求网页内容时,它会向服务器传递一个 HTTP_X_REQUESTED_WITH的参数,你可以利用如下方法判断某个请求是ajax请求还是普通请 求:
<font face="NSimsun">if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower ($_SERVER<br>['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’)<br>{<br>…这是一个ajax请求,然后…<br>}<br>else {<br>…这不是一个ajax请求,然后…<br>}</font>
利用这个来进行判断操作,可以使网页端的URL保持一致,但是能够对两种不同的请求却 能够得到不同内容的网页。即实现了用户操作优化,又不影响搜索引擎收录,我觉得是一个 很棒的解决方案!
这里有一个另外需要注意的问题,就是如果你的jquery请求是通过iframe打开网页的, 那么HTTP_X_REQUESTED_WITH参数不会被传递,也就是说你没有办法判断请求的类型。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools
