开发者

How to make browser not to refresh full page when it goes to URL?

I tried to understand - is it any method to ask browser not to refresh entire page when user clicks onto . Hash adding method is seen - I need another method, working with links without hashes. Ma开发者_运维问答y be any headers should be sent ? Or something another ?

I want to process GET queries returning only the part of HTML (or special js commands), not all page, and process it in AJAX-style.


You can ajaxify your links through jquery. Something like this:

$('a.ajax').click(function(ev){
    ev.preventDefault();
    var target=$(this).attr('data-target');
    var url=$(this).attr('href');
    $(target).load(url+' '+target);
}

This can be used in conduction with the following HTML:

<div id="output">
 Hello <a href="world.html" class="ajax" data-target="#output">World</a>
<div>

and inside world.html you would need to have:

<div id="output">
  Foo bar baz boo
</div>

In theory this should load content of the dif from "world" file into the div inside the first file, but I haven't tried it. I think it's what you need, because the regular link is still there, google will properly index this bypassing ajax and your users will be happy to see part of the page change.


you could make it 'fake' links doing something like this:

<span style="cursor:pointer;" onclick="loadPage('mypagename');">My Link</span>

The function then would be:

function loadPage(pageName){
    // do ajax call here using pageName var
}


You cannot prevent navigation when a user clicks a hyperlink with a URL. Using a hash value to navigate or having your hyperlinks invoke JavaScript is generally the way to add navigation inside of a single page.

However, if you're trying to convert an existing page that's not designed this way, you would have to use JavaScript to modify hyperlinks so they invoke Ajax. For example:

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {

    var oldUrl = links[i].getAttribute('href');
    links[i].setAttribute('href', 'javascript:void(0)');

    links[i].onclick = (function(url) {
        return function() {
            // Then you can do your AJAX code here
        }
    })(oldUrl);
}

I recommend that you don't do something like this, though, and rather create your page with an AJAX design in mind.


Changing the url without using hashes can be achieved with the Html5 History API: http://html5demos.com/history

Not supported by older browser though, so you must always have a fallback.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜