在PHP中检测AJAX请求

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值