今天需要将一个chat整合到客户的网站上去,实现网站的注册用户登录本网站之后点击某个链接能够直接登录到chat上去。我保留了chat原有的登录界面,采用JS技术当页面跳转过来的时候自动填充表单,并自动提交表单,从而实现网站用户无需再次登录即可进入chat。具体代码实现如下
JS代码
<script>
//取得cookie值
function getCookie(name){
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg)){
return unescape(arr[2]);
}else{
return null;
}
}
//表单自动提交函数
function tijiao(){
function sub(){
var a = document.getElementById('loginForm');
a.elements[2].value = getCookie('username');
a.elements[3].value = getCookie('username');
var opts = document.getElementById("channelField");
opts[1].selected = 'selected';
opts[0].selected = '';
a.submit();
}
setTimeout(sub,0);//以毫秒为单位的.1000代表一秒钟.根据你需要修改这个时间.
}
//点击button提交表单
function clickbutton(obj){
obj.onclick = function(){
obj.submit();
}
}
</script>
HTML代码
<form id="loginForm" name="loginForm" action="[LOGIN_URL/]" method="post" enctype="application/x-www-form-urlencoded">
<div id="loginFormContainer" style="margin:0px;padding-bottom: 10px;">
<input type="hidden" name="login" id="loginField" value="login"/>
<input type="hidden" name="redirect" id="redirectField" value="[REDIRECT_URL/]"/>
<div><label for="userNameField">[LANG]userName[/LANG]:</label>
<input type="text" name="userName" id="userNameField" maxlength="[USER_NAME_MAX_LENGTH/]"/></div><br />
<div><label for="passwordField">[LANG]password[/LANG]*:</label>
<input type="password" name="password" id="passwordField"/><span style="margin-left:4px; color: #339900;">默认是您的用户名</span></div><br />
<div><label for="channelField">[LANG]channel[/LANG]:</label>
<select name="channelName" id="channelField">[CHANNEL_OPTIONS/]</select></div><br />
<div><label for="languageSelection">[LANG]language[/LANG]:</label>
<select id="languageSelection" name="lang" onchange="ajaxChat.switchLanguage(this.value);">[LANGUAGE_OPTIONS/]</select></div><br />
<!--
<div><input type="submit" name="submit" style="width: 240px;height: 50px;background: url(../chat/img/bglogin2.png);background-repeat: no-repeat;border: 0px;" id="loginButton" value=""/></div>
-->
<div><button name="subButton" onclick="clickbutton(this);" style="width: 240px;height: 50px;background: url(../chat/img/bglogin2.png);background-repeat: no-repeat;border: 0px;" id="loginButton" value=""></button></div>
</div>
</form>
PS:
1. 要在body中加入onload="tijiao();"
- 另外表单的提交按钮(submit)需要隐去,不然会和js的submit()方法冲突,这里采用button提交,避免在自动登录失败时没有提交按钮