简体   繁体   English

Ajax页面加载,刷新页面时消失

[英]Ajax Page load, gone when refresh page

I was working with Ajax now and I have this piece of code: 我现在正在使用Ajax,我有这段代码:

<script type="text/javascript">
function load(file,container)
       {
var xmlhttp, newhash = '';

if (window.XMLHttpRequest){  xmlhttp=new XMLHttpRequest();}
if (window.ActiveXObject) {  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

xmlhttp.onreadystatechange= function (){
      if(xmlhttp.readyState==4 && xmlhttp.status==200)
      {  document.getElementById(container).innerHTML=xmlhttp.responseText;
    } else {
        document.getElementById(container).innerHTML='<div style="padding:10px">       <p>Please upgrade your web browser to support modern technology.</p></div>';
        }
    }
xmlhttp.open("GET",file,true);
xmlhttp.send(null);
}
</script>
<script type="text/javascript" src="jquery.js"></script>
<ul>
<li><a href="#" onclick="load('home.php','ajax');return false;">Home</a><li/>
</ul>
       <div id="ajax">



</div>  

Sorry it's my first post but my real concern is that, the page can be loaded but then when I refresh the page the page will just gone,. 抱歉,这是我的第一篇文章,但我真正关心的是,可以加载页面,但是当我刷新页面时,页面就消失了。 I tried to put a hash on the url but then it still doesn't work. 我试图在网址上添加一个哈希,但是它仍然无法正常工作。

Your content is being loaded only on the button click. 仅在单击按钮时才加载您的内容。 You'll need to tell the browser to auto-load* the content depending on your hash. 您需要告诉浏览器根据您的哈希值自动加载*内容。

For this, you can: 为此,您可以:

1 - Give a hash to your link, by specifying it in the href attrbiute. 1-通过在href属性中指定哈希值来为您的链接提供哈希值。 Remove the return false; 删除return false; from your onclick to ensure the page url changes to #home 通过onclick来确保页面URL更改为#home

<a href="#home" onclick="load('home.php','ajax');">Home</a>

2 - Add an onload handler that auto-loads the page specified in the hash. 2-添加一个onload处理程序,该处理程序自动加载哈希中指定的页面。

<body onload="loadHash();">

3 - Write the auto hash loader 3-编写自动哈希加载器

<script>
function loadHash() {
    var hash = window.location.href.split('#');
    if(hash.length == 2) {
        load(hash[1] + '.php','ajax');
    }
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM