使用Ajax加载外部页面内容

时间:2010-11-10 03:11:41

标签: ajax tumblr

只是为了娱乐,学习,美学等。我一直在使用Ajax来修改我的Tumblr主题。我要做的是将下一页的内容加载到当前页面上的div中。这样人们可以在主页面上浏览不同的页面。博客的主页是http://diaryofthedead.co.cc/。页面已编号。第二页是http://diaryofthedead.co.cc/page/2,依此类推。

Ajax脚本(我在Google上发现,老实说,我不太了解它)是:

<script language="javascript">
function Next() {
    if (location.href == 'http://diaryofthedead.co.cc/') {
        var pagenum = '2';
        var next = 'page/'+pagenum;
        ajaxpagefetcher('container',next,true);
        pagenum = pagenum += 1
    }
    else {
        pagenum = location.href.match(/\/page\/(.*)/)[1];
        plus = pagenum += 1;
        var next = 'page/'+plus;
        ajaxpagefetcher('container',next,true);
    }
}
var ajaxpagefetcher={
loadingmessage: "Loading Page, please wait...",
exfilesadded: "",

connect:function(containerid, pageurl, bustcache, jsfiles, cssfiles){
    var page_request = false
    var bustcacheparameter=""
    if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
        page_request = new XMLHttpRequest()
    else if (window.ActiveXObject){ // if IE6 or below
        try {
        page_request = new ActiveXObject("Msxml2.XMLHTTP")
        } 
        catch (e){
            try{
            page_request = new ActiveXObject("Microsoft.XMLHTTP")
            }
            catch (e){}
        }
    }
    else
        return false
    var ajaxfriendlyurl=pageurl.replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/") 
    page_request.onreadystatechange=function(){ajaxpagefetcher.loadpage(page_request, containerid, pageurl, jsfiles, cssfiles)}
    if (bustcache) //if bust caching of external page
        bustcacheparameter=(ajaxfriendlyurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
    document.getElementById(containerid).innerHTML=ajaxpagefetcher.loadingmessage //Display "fetching page message"
    page_request.open('GET', ajaxfriendlyurl+bustcacheparameter, true)
    page_request.send(null)
},

loadpage:function(page_request, containerid, pageurl, jsfiles, cssfiles){
    if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
        document.getElementById(containerid).innerHTML=page_request.responseText
        for (var i=0; i<jsfiles.length; i++)
            this.loadjscssfile(jsfiles[i], "js")
        for (var i=0; i<cssfiles.length; i++)
            this.loadjscssfile(cssfiles[i], "css")
        this.pageloadaction(pageurl) //invoke custom "onpageload" event
    }
},

createjscssfile:function(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    return fileref
},

loadjscssfile:function(filename, filetype){ //load or replace (if already exists) external .js and .css files
    if (this.exfilesadded.indexOf("["+filename+"]")==-1){ //if desired file to load hasnt already been loaded
        var newelement=this.createjscssfile(filename, filetype)
        document.getElementsByTagName("head")[0].appendChild(newelement)
        this.exfilesadded+="["+filename+"]" //remember this file as being added
    }
    else{ //if file has been loaded already (replace/ refresh it)
    var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
    var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
    var allsuspects=document.getElementsByTagName(targetelement)
    for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
    if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1){
    var newelement=this.createjscssfile(filename, filetype)
    allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
    }
        }
 }
},


pageloadaction:function(pageurl){
    this.onpageload(pageurl) //call customize onpageload() function when an ajax page is fetched/ loaded
},

onpageload:function(pageurl){
 //do nothing by default
},

load:function(containerid, pageurl, bustcache, jsfiles, cssfiles){
    var jsfiles=(typeof jsfiles=="undefined" || jsfiles=="")? [] : jsfiles
    var cssfiles=(typeof cssfiles=="undefined" || cssfiles=="")? [] : cssfiles
    this.connect(containerid, pageurl, bustcache, jsfiles, cssfiles)
}

} //End object

//Sample usage:
//1) ajaxpagefetcher.load("mydiv", "content.htm", true)
//2) ajaxpagefetcher.load("mydiv2", "content.htm", true, ["external.js"])
//3) ajaxpagefetcher.load("mydiv2", "content.htm", true, ["external.js"], ["external.css"])
//4) ajaxpagefetcher.load("mydiv2", "content.htm", true, ["external.js", "external2.js"])
//5) ajaxpagefetcher.load("mydiv2", "content.htm", true, "", ["external.css", "external2.css"])
</script>

函数Next()是我自己设计的,显然问题出在哪里。我在链接中使用它作为onclick事件:

<a href="javascript:void();" onclick="Next()">Click This</a>

当我点击它时,可悲的是,它绝对没有。我不确定到底出了什么问题,我希望有人可以指出我的方向错误。

2 个答案:

答案 0 :(得分:0)

这不是您正在寻找的答案,但我强烈建议您尝试使用jQuery:http://www.jquery.com/

你所拥有的代码令人难以置信的复杂,并且可以通过jQuery的帮助程序进行简化。 (我相信你会同意需要 10 行的异常捕获来打开一个简单的连接有点傻.jQuery摘要这个。)

此外,还有一个提示:如果您要在其他域中加载页面,则需要使用getJSON() ...

答案 1 :(得分:0)

您可以使用JQuery Load方法,也可以使用$.get方法。