今天做项目时候遇到一个问题,由于采用了生成静态的CMS系统,但是页面头部需要显示用户登录的信息,也就是,没有登录时,显示登录框,用户登录后,则显示登录信息。于是用到了js调用php文件的方法。但是由于浏览器的缓存,用户登录后常常还是显示登录框,因为js文件被缓存,没有重新下载。
由于js文件是用<script>标签引入的,无法加随机数参数以使每次都重新下载。经过研究采用以下方法达到目的:
这里是头部的html代码:
<tablewidth="770"border="0"align="center"cellpadding="0"cellspacing="0">
<tr>
<tdwidth="377"height="35"align="left"nowrap="nowrap"id="user_status_div">
<scripttype="text/javascript">...
varjsFile=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>
<tdwidth="393"align="right"nowrap="nowrap"><ahref="http://www.nmc.gov.cn/weatherdetail/57494.html"title="点击查看详细天气预报"target="_blank">武汉</a><spanstyle="font-size:9pt">
<scriptsrc="/weather.php"></script>
</span><span> <ahref="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');returnfalse;"
href="http://www.qg.org.cn#">设为首页</a> <ahref='#'onClick="javascript:window.external.AddFavorite('{dede:globalname="cfg_basehost"/}','{dede:globalname="cfg_webname"/}');">收藏本站</a></span></td>
</tr>
</table>
这里是生成调用js的php文件:
<?php
if(!isset($_COOKIE['DedeUserID'])||$_COOKIE['DedeUserID']=='')
{
?>
document.getElementById("user_status_div").innerHTML='<formid="form1"name="form1"method="post"action="/member/index_do.php">[<ahref="/member/index_do.php?fmdo=user&dopost=regnew">会员注册</a>] 用户名<inputtype="text"name="userid"id="userid"class="user"/> 密码<inputname="pwd"type="password"class="user"/> <inputtype="submit"name="btnsubmit"id="btnsubmit"value="登录"class="login"/><inputtype="hidden"name="fmdo"value="login"><inputtype="hidden"name="dopost"value="login"><inputtype="hidden"name="gourl"id="gourl"value="'+window.location.href+'"><inputname="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=newDedeSql(false);
$query="SelectuseridFrom#@__memberwhereid=".$_COOKIE['DedeUserID'];
$username=$dsql->GetOne($query);
$dsql->Close();
?>
document.getElementById("user_status_div").innerHTML='欢迎您<?phpecho($username['userid']);?>[<ahref="/member/index.php">用户中心</a>][<ahref="/member/index.php?uid=<?phpecho($username['userid']);?>">我的空间</a>][<ahref="/member/index_do.php?fmdo=login&dopost=exit&forward='+window.location.href+'">退出登录</a>]';
<?php
}
?>
注意这里采用了crateElement方法来动态创建<script>标签,达到了添加随机参数的目的。另外,在调用的js文件中,必须采用innerHTML方法,而不是直接document.write,否则排版可能会不正确。
希望此雕虫小技能给你带来帮助。
191

被折叠的 条评论
为什么被折叠?



