开发者

transform jquery ajax into standard javascript

Jquery is q开发者_C百科uite heavy and bloated. Unfortunately I do not know how to code "real" javascript.

I have this code:

$(document).ready(function () {
    if(window.navigator.standalone){
        $('a').click(function(e) {
            e.preventDefault();
            $("body").load(this.href);
        });
    }
}); 

Could somebody help me along the way to transform this into real javascript? how would i replace load()? Thanks a lot :)


Not terribly complicated:

window.onload= function() {
    if (!navigator.standalone) return;
    for (var i= document.links.length; i-->0;) {
        document.links[i].onclick= function() {
            var req= new XMLHttpRequest();
            req.onreadystatechange= function() {
                if (this.readyState!==4) return;
                document.body.innerHTML= this.responseText;
            };
            req.open('GET', this.href, true);
            req.send();
            return false;
        };
    }
};

To make XMLHttpRequest work on IE6, if that's a concern for you at all, you would need to define this first:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
       return new ActiveXObject('MSXML2.XMLHttp');
    };
}

That's really all there is to it.

But for general-purpose web pages you should never do this; not in native JavaScript and not in jQuery. loading content into the existing page subverts the browser's navigational abilities and replaces them with nothing. The back and forward buttons now don't work any more. The user can't bookmark their favourite pages, or send links to anyone else. This is a re-invention of the worst usability problems of frames, and shouldn't be done on the open web without a lot of extra work to implement HTML5 history-navigation and hashbang fallback nav for search engines.


Isn't jQuery real javascript for you? If you mean raw javascript without any framework then you need a XmlHttpRequest (prepare yourself for writing sheer amount of code, also prepare yourself for this code not working identically among different browsers, getting errors, headaches, etc ...).

Conclusion: use jQuery and be happy.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜