dplsnw7329 2015-10-25 15:41
浏览 45
已采纳

如果它不是ajax请求,则响应不同的html

I asked this before and I have got several negative scores but this time I ask it more clear.

I have this structure on a website:

  • Mainpage (All resources and scripts are in this page)
    • All Other pages (HTML just contains elements of that specific page)

If user clicks on mainpage anchors to other pages, AJAX function that is embed to On click event will run and URL address will change using Window.history.PushState .

The problem is what we can do if user enters URL of other pages instead clicking on anchors? For example if user enters: http://example.com/pages/about then only elements of that page will load without resources and scripts of mainpage that is needed.

I think to a solution something like this:

  1. Detect if user enters URL instead clicking on anchors.(detect HTTP request)
  2. Load resources included in mainpage if it is a HTTP request.

Could this solution be in Client-side(javascript) way? I know a little PHP too.

Take a look at Cloudflare panel to see what i mean: https://www.cloudflare.com/a/overview

  • 写回答

1条回答 默认 最新

  • doudu2404 2015-10-27 21:01
    关注

    I did a little research(Thanks to comments) and this is my preferable solution. I didn't want to change markup so Template engines wasn't my choice.

    1.Write this PHP Script in save it in a PHP file.

    <?php
    
    /* Detect AJAX */
    
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        /* If it is AJAX do this */
    }
    
    else {
    /* If it is not AJAX do this; In my case I did echo all scripts and resources that I wanted to be in AJAX addresses */
        echo '
            <script src="example.js"></script>
        ';
    }
    

    2.Link above PHP script file in pages that have both AJAX and HTTP request. In my case I put that is all other pages instead Main-page.

    <?php include "../script.php"; ?>
    

    3.Config your webserver to support PHP scripts in HTML file extension. My webserver was Apache so I wrote this line in .htaccess file.

    AddType application/x-httpd-php .htm .html
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题