有没有可靠的方法来了解请求是否在PHP中的Ajax上下文中?

时间:2021-12-01 09:10:38

I need to deal with these two cases differently,is there a good solution?

我需要以不同的方式处理这两种情况,有一个很好的解决方案吗?

2 个解决方案

#1


6  

if ($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') { /* ajax request */ }

#2


3  

I can think of 2 ways to accomplish this:

我可以想到两种方法来实现这个目标:

  • On the AJAX side you could set a custom HTTP header with XMLHttpRequest.setRequestHeader() and then check for the presence of that header on the PHP side with getallheaders() to indicate that the request was made by an AJAX client. If your php script doesn't find the custom header, you can consider it to be a non-AJAX request.

    在AJAX方面,您可以使用XMLHttpRequest.setRequestHeader()设置自定义HTTP标头,然后使用getallheaders()检查PHP端是否存在该标头,以指示该请求是由AJAX客户端发出的。如果您的php脚本找不到自定义标头,您可以将其视为非AJAX请求。

  • When you create the request in your code, you could simply tack on a querystring variable to indicate the nature of the request. eg. http://example.com/process?ajax=true for an AJAX reqeust or http://example.com/process?ajax=false for a non-AJAX request.

    在代码中创建请求时,您可以简单地使用querystring变量来指示请求的性质。例如。 http://example.com/process?ajax=true用于AJAX请求或http://example.com/process?ajax=false用于非AJAX请求。

#1


6  

if ($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') { /* ajax request */ }

#2


3  

I can think of 2 ways to accomplish this:

我可以想到两种方法来实现这个目标:

  • On the AJAX side you could set a custom HTTP header with XMLHttpRequest.setRequestHeader() and then check for the presence of that header on the PHP side with getallheaders() to indicate that the request was made by an AJAX client. If your php script doesn't find the custom header, you can consider it to be a non-AJAX request.

    在AJAX方面,您可以使用XMLHttpRequest.setRequestHeader()设置自定义HTTP标头,然后使用getallheaders()检查PHP端是否存在该标头,以指示该请求是由AJAX客户端发出的。如果您的php脚本找不到自定义标头,您可以将其视为非AJAX请求。

  • When you create the request in your code, you could simply tack on a querystring variable to indicate the nature of the request. eg. http://example.com/process?ajax=true for an AJAX reqeust or http://example.com/process?ajax=false for a non-AJAX request.

    在代码中创建请求时,您可以简单地使用querystring变量来指示请求的性质。例如。 http://example.com/process?ajax=true用于AJAX请求或http://example.com/process?ajax=false用于非AJAX请求。