Lifehacker使用Ajax实现url更改 [英] Lifehacker implemention of url change with Ajax

查看:127
本文介绍了Lifehacker使用Ajax实现url更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到Lifehacker能够在使用AJAX更新部分页面时更改URL。我想这可以使用HTML5或history.js插件来实现,但我猜lifehacker都没有使用。

I see that Lifehacker is able to change the url while using AJAX to update part of the page. I guess that can be implemented using HTML5 or history.js plugin, but I guess lifehacker is using neither.

有没有人知道他们是怎么做的?
我是AJAX的新手,只是设法使用Ajax更新部分页面。

Does any one has a clue on how they do it? I am new to AJAX and just managed to update part of the page using Ajax.

谢谢@罗宾安德森详细一步一步的算法。我试了一下它工作正常。但是,在我可以在生产中测试它之前,我想用你运行我的代码。我做对了吗?

Thank you @Robin Anderson for a detailed step by step algo. I tried it and it is working fine. However, before I can test it on production, I would like to run by you the code that I have. Did I do everything right?

<script type="text/javascript">  
var httpRequest;  
var globalurl;
    function makeRequest(url) {  
    globalurl = url;
    /* my custom script that retrieves original page without formatting (just data, no templates) */
    finalurl = '/content.php?fname=' + url ;

    if(window.XMLHttpRequest){httpRequest=new XMLHttpRequest}else if(window.ActiveXObject){try{httpRequest=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{httpRequest=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}  

    /* if no html5 support, just load the page without ajax*/
    if (!(httpRequest && window.history && window.history.pushState)) {     
            document.href = url;
            return false;  
    } 

    httpRequest.onreadystatechange = alertContents;  
    alert(finalurl);    /* to make sure, content is being retrieved from ajax */
    httpRequest.open('GET', finalurl);  
    httpRequest.send();  
    } 

    /* for support to back button and forward button in browser */
    window.onpopstate = function(event) {
            if (event.state !== null) {
                    document.getElementById("ajright").innerHTML = event.state.data;
            } else {
                    document.location.href = globalurl;
                    return false;
            };
    };    

    /* display content in div */
    function alertContents() {  
            if (httpRequest.readyState === 4) {  
            if (httpRequest.status === 200) {  
                    var stateObj = { data: httpRequest.responseText};
                    history.pushState(stateObj, "", globalurl);     
                    document.getElementById("ajright").innerHTML = httpRequest.responseText;
            } else {  
                    alert('There was a problem with the request.');  
            }  
            }  
    }  
    </script> 

PS:我不知道如何在评论中粘贴代码,所以我在这里添加了它。

PS: I do not know how to paste code in comment, so I added it here.

推荐答案

为了在浏览器中使用历史API,即使它是HTML5,也不要求将标记作为HTML5功能。

It is not an requirement to have the markup as HTML5 in order to use the history API in the browser even if it is an HTML5 feature.

使用AJAX加载所有页面转换的一个非常快速和简单的实现是:

One really quick and simple implementation of making all page transistions load with AJAX is:


  1. 连接所有链接,除非rel =external存在于函数ChangePage

  2. 当触发ChangePage时,检查浏览器是否支持历史API。 / li>
  3. 如果不支持历史记录API,请按推送标签或将正常的整页加载作为后备。

  4. 如果支持历史记录API:

  1. Hook up all links except where rel="external" exist to the function "ChangePage"
  2. When ChangePage is triggered, check if history API is supported in the browser.
  3. If history API isn't supported, do either push a hashtag or make a normal full page load as fallback.
  4. If history API is supported:

  1. 防止正常链接行为。

  2. 将新网址推送到浏览器历史记录。

  3. 向新网址发出AJAX请求并获取其内容。

  4. 查找您的内容div(或simila)响应中的r元素,从中获取HTML并将当前页面上相应元素的HTML替换为新元素。

  1. Prevent the normal link behaviour.
  2. Push the new URL to the browser history.
  3. Make a AJAX request to the new URL and fetch its content.
  4. Look for your content div (or similar element) in the response, take the HTML from that and replace the HTML of the corresponding element on the current page with the new one.


这将很容易实现,易于管理缓存并与Google的机器人配合使用,缺点是不是优化而且会有一些开销更改页面时的响应(与更复杂的解决方案相比)。

This will be easy to implement, easy to manage caches and work well with Google's robots, the downside is that is isn't that "optimized" and it will be some overhead on the responses (compared to a more complex solution) when you change pages.

还具有向后兼容性,因此旧浏览器或非JavaScript访问者将正常页面加载。

Will also have backward compatibility, so old browsers or "non javascript visitors" will just get normal page loads.

有关主题的有趣链接

  • History API Compatibility in different browsers
  • Mozillas documentation of the History API

修改:

值得一提的另一件事是,你不应该将它与ASP .Net Web Forms应用程序一起使用,可能会搞砸回发处理。

Another thing worth mentioning is that you shouldn't use this together with ASP .Net Web Forms applications, will probably screw up the postback handling.

代码添加:

我已经整理了一个这个功能的小演示,你可以在这里找到

它只是使用HTML,Javascript(jQuery)和一点点CSS,我可能会建议你在使用之前测试它。但是我已经在Chrome中检查了一些它似乎工作正常。

It simply uses HTML, Javascript (jQuery) and a tiny bit of CSS, I would probably recommend you to test it before using it. But I have checked it some in Chrome and it seems to work decent.

我建议的一些测试是:


  • 在优秀的浏览器,Chrome和Firefox中进行测试。

  • 在IE7等传统浏览器中测试

  • 在没有启用Javascript的情况下测试它(只需安装Noscript或类似于Chrome / Firefox)

这是我用来实现此目的的javascript,你可以在上面的演示中找到完整的源代码。

Here is the javascript I used to achieve this, you can find the full source in the demo above.

/*
    The arguments are:          
        url: The url to pull new content from
        doPushState: If a new state should be pushed to the browser, true on links and false on normal state changes such as forward and back.
*/
function changePage(url, doPushState, defaultEvent)
{
    if (!history.pushState) { //Compatability check
        return true; //pushState isn't supported, fallback to normal page load
    }

    if (defaultEvent != null) { 
        defaultEvent.preventDefault(); //Someone passed in a default event, stop it from executing
    }

    if (doPushState) {  //If we are supposed to push the state or not
        var stateObj = { type: "custom" }; 
        history.pushState(stateObj, "Title", url); //Push the new state to the browser
    }               

    //Make a GET request to the url which was passed in
    $.get(url, function(response) {             
        var newContent = $(response).find(".content");      //Find the content section of the response
        var contentWrapper = $("#content-wrapper");         //Find the content-wrapper where we are supposed to change the content.
        var oldContent = contentWrapper.find(".content");   //Find the old content which we should replace.

        oldContent.fadeOut(300, function() { //Make a pretty fade out of the old content
            oldContent.remove(); //Remove it once it is done
            contentWrapper.append(newContent.hide()); //Add our new content, hidden
            newContent.fadeIn(300); //Fade it in!
        });

    });
}


//We hook up our events in here
$(function() {
    $(".generated").html(new Date().getTime()); //This is just to present that it's actually working.

    //Bind all links to use our changePage function except rel="external"
    $("a[rel!='external']").live("click", function (e) { 
        changePage($(this).attr("href"), true, e);
    });

    //Bind "popstate", it is the browsers back and forward
    window.onpopstate = function (e) { 
        if (e.state != null) {
            changePage(document.location, false, null); 
        }
    }
}); 

这篇关于Lifehacker使用Ajax实现url更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆