今天做項目時候遇到一個問題,由於采用了生成靜態的CMS系統,但是頁面頭部需要顯示用戶登錄的信息,也就是,沒有登錄時,顯示登錄框,用戶登錄后,則顯 示登錄信息。於是用到了js調用php文件的方法。但是由於瀏覽器的緩存,用戶登錄后常常還是顯示登錄框,因為js文件被緩存,沒有重新下載。
由於js文件是用<script>標簽引入的,無法加隨機數參數以使每次都重新下載。經過研究采用以下方法達到目的:
這里是頭部的html代碼:
<table width="770" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="377" height="35" align="left" nowrap="nowrap" id="user_status_div"> <script type="text/javascript"> var jsFile = document.createElement("script"); jsFile.setAttribute("type","text/javascript"); jsFile.setAttribute("src","/member/user_status_js.php?random="+Math.random()); document.getElementById('user_status_div').appendChild(jsFile); </script> </td> <td width="393" align="right" nowrap="nowrap"><a href="http://www.nmc.gov.cn/weatherdetail/57494.html" title="點擊查看詳細天氣預報" target="_blank">武漢</a><span style="font-size: 9pt"> <script src="/weather.php"></script> </span><span> <a href="http://www.nmc.gov.cn/weatherdetail/57494.html" title="點擊查看詳細天氣預報" target="_blank">更多</a> <a onclick="this.style.behavior='url(#default#homepage)';this.sethomepage('http://www.cnmamia.com');return false;" href="http://www.qg.org.cn#">設為首頁</a> <a href='#' onClick="javascript:window.external.AddFavorite('{dede:global name="cfg_basehost"/}','{dede:global name="cfg_webname"/}');">收藏本站</a></span></td> </tr> </table>
這里是生成調用js的php文件:
<?php if(!isset($_COOKIE['DedeUserID'])||$_COOKIE['DedeUserID']=='') { ?> document.getElementById("user_status_div").innerHTML='<form id="form1" name="form1" method="post" action="/member/index_do.php">[<a href="/member/index_do.php?fmdo=user&dopost=regnew">會員注冊</a>] 用戶名<input type="text" name="userid" id="userid" class="user" /> 密碼<input name="pwd" type="password" class="user" /> <input type="submit" name="btnsubmit" id="btnsubmit" value="登錄" class="login" /><input type="hidden" name="fmdo" value="login"><input type="hidden" name="dopost" value="login"><input type="hidden" name="gourl" id="gourl" value="'+window.location.href+'"><input name="nochvd" type="hidden" id="nochvd" value="1" /></form>'; <?php } else { require_once(dirname(__FILE__)."/config.php"); require_once(dirname(__FILE__)."/../include/config_base.php"); $dsql = new DedeSql(false); $query="Select userid From #@__member where id=".$_COOKIE['DedeUserID']; $username = $dsql->GetOne($query); $dsql->Close(); ?> document.getElementById("user_status_div").innerHTML='歡迎您 <?php echo($username['userid']);?> [<a href="/member/index.php">用戶中心</a>] [<a href="/member/index.php?uid=<?php echo($username['userid']);?>">我的空間</a>] [<a href="/member/index_do.php?fmdo=login&dopost=exit&forward='+window.location.href+'">退出登錄</a>]'; <?php } ?>
注意這里采用了crateElement方法來動態創建<script>標簽,達到了添加隨機參數的目的。另外,在調用的js文件中,必須采用innerHTML方法,而不是直接document.write,否則排版可能會不正確。