dongling2545 2019-07-03 08:22
浏览 88
已采纳

仅在ajax调用时显示php页面的内容,而不是在地址栏上直接显示

I was wondering if there is a way to check if a PHP page was called by an Ajax request. I have a page that shows a form for update some data on database (update.php) but I want to make it accessible only if it was called by a page called "change_image.php", because I won't show the form if called by direct link, as it will be without CSS and javascript, because they are included in the first page (update.php).

I saw this answer on StackOverflow, but it is without explanation and I don't know if it is the right way to do that: Link to answer

The code of the answer is that:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/** Yes, it was an ajax call! */ 
/* I can call create_mosaic() function here 
 after checking if images have been loaded*/
}
  • 写回答

2条回答 默认 最新

  • doufu9836 2019-07-03 08:39
    关注
    public function isAJAX() {
      return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
    }
    

    This is a slightly different version. First checking if HTTP_X_REQUESTED_WITH is set and equals XMLHttpRequest which is a flag that most frameworks use (send) with their AJAX requests.

    You could also simply send your own variable with every AJAX request you make and check it on your AJAX endpoint.

    For example:

    $.ajax({
      url: url,
      data: {
        requestType: 'AJAX'
      },
      type: 'GET'
    });
    

    And on your PHP endpoint:

    if (isset($_GET['requestType']) && $_GET['requestType'] === 'AJAX') {
    
      // This is an AJAX request
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ssh登录页面的问题
  • ¥60 渗透一个指定银行app,拿到客户信息,需要什么级别
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图