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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度