触发javascript事件以在具有ajax响应的另一个div上显示错误文本

时间:2012-04-17 05:46:55

标签: php javascript ajax

我正面临一个JavaScript的奇怪问题,我正在研究一个ajax数据库。数据库的登录表单使用ajax请求/函数将数据发送到PHP控制器。我在登录页面上有一个错误显示器不可见div(名为errorDiv)。 errorDiv html是:

<div id="errorDiv" style="visibility:hidden; display:none">
...
</div>

当登录表单中的用户名和密码字段都为空时,我需要PHP控制器响应,显示登录表单并运行JavaScript函数“DisplayLoginError()”,这将使错误div可见并显示错误消息(请填写两个字段)在error-div.DisplayLoginError()函数中的代码是:

function DisplayLoginError()
{
document.getElementById('errorDiv').style.visibility="visible";
document.getElementById('errorDiv').style.display="block";
document.getElementById('errorDiv').innerHTML = "<?php echo $loginerror; ?>";
}

php控制器代码是:

if(isset($_REQUEST['login']))
{
if(isset($_REQUEST['username']) && isset($_REQUEST['password']))
    {
    .....Both the fields are filled...
    }
else   /*===Error:Any of the username or password field has  been left empty====*/
    {
    $loginerror='Please fill both the Fields to login.';
    include $_SERVER['DOCUMENT_ROOT'].'\hospital\includes\collegedata\login-form.html.php';
    }
}

现在的问题是无法完成,因为大多数javascript事件都是用户操作触发的。对于该时间,我已经为表单标记分配了一个mouseover事件,该事件在触发时运行DisplayLoginError函数并在errorDiv中显示错误。

<form onmouseover="DisplayLoginError()"> ..... </form>

但它不是正确的解决方案。我需要一个可以运行此功能的事件,同时只加载登录div而不是整个页面。我不能在这里使用onload事件作为ajax数据库,其中主页仍然只是div的变化。可能是时间事件可以用于此目的...我不确定...可能有更好的解决方案......我怎么能用ajax做到?

1 个答案:

答案 0 :(得分:1)

您可以在javascript中使用丢失焦点事件。我无法清楚地理解您的查询。所以这只是一个建议。

<div id='errorDiv' >
</div>
Username : <input type="text" name="username" id="uname" onBlur="checkUsername();">
Password : <input type="text" name="password" id="pword" onBlur="checkValues();">

<script type="text/javascript">
function checkValues()
{
    uname = document.getElementById('uname').value;
    pword = document.getElementById('pword').value;
    if(uname=="" || pword=="") {
        document.getElementById('errorDiv').innerHTML="Please fill both the fields";
    }else{
        document.getElementById('errorDiv').innerHTML="";
    }
}
function checkUsername()
{
    uname = document.getElementById('uname').value;
    if(uname==""){
        document.getElementById('errorDiv').innerHTML="Please enter username";
    }else{
        document.getElementById('errorDiv').innerHTML="";
    }
}
</script>