开发者

Need help with jQuery syntax to change URL

开发者 https://www.devze.com 2023-03-24 00:10 出处:网络
Using jQuery, is there a way I can make every http://www.mywebsite.com/page/ become http://www.mywebsite.com/#page for the visitors and make sure the Facebook URL L开发者_如何转开发inter (http://devel

Using jQuery, is there a way I can make every http://www.mywebsite.com/page/ become http://www.mywebsite.com/#page for the visitors and make sure the Facebook URL L开发者_如何转开发inter (http://developers.facebook.com/tools/lint) is still able to read the tags in http://www.mywebsite.com/page/ ?


I'm not sure I fully understand your question. A client-side library cannot change the path part of the URL without causing the browser to fetch a different page from the server.

So, if the user goes to http://www.mywebsite.com/page/, then you could use client-side javascript to redirect the user to http://www.mywebsite.com/#page/, but that would cause the browser to load the page http://www.mywebsite.com/ and then try to find the #page fragment in that page. If you want the browser to reload http://www.mywebsite.com/#page/, then that is indeed what would happen.

FB will not run javascript on your page so if FB goes to http://www.mywebsite.com/page/, that's what it will see (it will not get redirected like a regular browser would).

If you want to do a forceful redirect with javascript, you can put this code in your page:

var path = window.location.pathname;
if (path.search(/^\/page\/?$/) >= 0) {
    window.location.replace("http://www.mywebsite.com/#page/");
}

This code tests to see if the pathname on the URL of the page is /page or /page/ and if so, then does the redirect.


<script>
$(window).load(function(){
    var pieces = location.href.split('/');
    if (pieces[3].indexOf('#!') !== 0) {
        if (location.href.indexOf('#!') != -1) {
            pieces = location.href.replace('#!','').split('/');
        }
        pieces[3] = '#!/'+pieces[3];
        location.href = pieces.join('/');
    }
});
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消