Creating Ajax website with links of multiple subfolders is failing

后端 未结 1 481
暖寄归人
暖寄归人 2021-01-27 07:30

I\'m trying to create a site that is loading all it\'s content via Ajax. So let\'s say the site is www.abc.net

相关标签:
1条回答
  • 2021-01-27 08:04

    Update your .htaccess file like so:

    RewriteEngine On 
    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
    

    This will redirect all relevant server calls to index.php?url=<rest of the url>.

    Now, rename your index.html to index.php (we need to write a little php code).

    In your JavaScript write:

    var url = "<?php echo $_GET['url']; ?>";
    

    And there you have it. You can now split the string by '/' delimiter to find all your needed components.

    As per your example, the following url: abc.net/somesubsite/someother will redirect to index.php and the url variable will hold somesubsite/someother.

    You can then use url.split('/') to get all "subfolders" in an array.

    You will also have to override all links' behavior in your site:

    1. Prevent the normal action
    2. Load the ajax content
    3. pushState to change the url

    like so:

    $('a').on('click', function(e){ 
        e.preventDefault(); // 1
        var $url = this.href;
        loadContent($url); // 2 
        window.history.pushState("object or string", "Title", $url); // 3        
    });
    
    0 讨论(0)
提交回复
热议问题