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 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频