在PHP中检测AJAX请求

    技术2022-07-11  135

    I like using the same PHP script for both AJAX and non-AJAX content requests. Using one script just makes everything easier because it's only one file to update/edit and it's one more cache-able request. One way to try detect an AJAX request (as opposed to a regular page load) is by using the following PHP code:

    我喜欢对AJAX和非AJAX内容请求使用相同PHP脚本。 使用一个脚本会使一切变得更容易,因为它只是一个文件要更新/编辑,并且是另一个可以缓存的请求。 尝试检测AJAX请求(与常规页面加载相反)的一种方法是使用以下PHP代码:

    /* decide what the content should be up here .... */ $content = get_content(); //generic function; /* AJAX check */ if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { /* special ajax here */ die($content); } /* not ajax, do more.... */

    $_SERVER['HTTP_X_REQUESTED_WITH'] is the golden ticket but not all servers provide this variable so having other checks in place will be important.

    $_SERVER['HTTP_X_REQUESTED_WITH']是黄金票,但并非所有服务器都提供此变量,因此进行其他检查将很重要。

    翻译自: https://davidwalsh.name/detect-ajax

    Processed: 0.009, SQL: 9