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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵