简体   繁体   中英

Respond different html if it's not ajax request

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM