问题
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.
I have abc.net/index.html and this file shall always being called, whatever URL(folder/file) was typed in. So e.g. abc.net/somesubsite was called, the URL should stay as it is and just calling the index.html.
The idea is now to look which URL was called and to handle that with jQuery and showing the specific div. In that way a direct link would be easily possible.
Well my issue is that I'm not able to let the URL stay as it is and when having abc.net/somesubsite/someother then I get an server error. I was playing around with htaccess but it feels that it's not really a perfect solution.
Is there good way to do that? It is like this site but I want to be able to handle folder/subfolder which is not possible there. I'm interested in any solution, it's also no problem to have different html files that are loaded if really needed. But if possible I would like to have all in one file.
回答1:
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:
- Prevent the normal action
- Load the ajax content
- 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
});
来源:https://stackoverflow.com/questions/28593650/creating-ajax-website-with-links-of-multiple-subfolders-is-failing