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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?