exit()函数的替代方案?

时间:2015-04-17 13:53:20

标签: javascript php

如果不满足条件,我试图更改按钮的类(if(strlen($ username)< 5))这是我的代码:

    if( strlen($username) < 5 ){
        echo '<span  class = "glyphicon glyphicon-remove" style = "color:red"> More then 4 caracters </span>';
        $buttonClass = 'btn btn-primary disabled';
        exit();
    } 
    elseif( is_numeric($username[0]) ) {
        echo '<span  class = "glyphicon glyphicon-remove" style = "color:red"> First character mst be a letter </span>';
        $buttonClass = 'btn btn-primary disabled';
        exit();
    }
    elseif($check < 1){
        echo '<span class = "glyphicon glyphicon-ok" style = "color:green"> ' . $username . ' is available</span>';
    }else{
        echo '<span  class = "glyphicon glyphicon-remove" style = "color:red"> This username is already taken </span>';
        $buttonClass = 'btn btn-primary disabled';
        exit();
    }
}
?>

<script type="text/javascript" language = "javascript">

        var status = document.getElementById("usernamestatus");
        var u = document.getElementById("username").value;
        if(u != "") {
            hr.open("POST","register.php",true);
            hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            hr.onreadystatechange = function(){
                if(hr.readyState == 4 && hr.status == 200){
                    status.innerHTML = hr.responseText;
                }
            }

</script>

现在我知道exit()功能有什么关系,但是如果我不把它放在页面上的html上两次,我怎么能阻止这种情况发生呢?请有人帮忙吗?

2 个答案:

答案 0 :(得分:3)

您的困惑在于您使用相同的脚本来处理初始表单和AJAX响应。 AJAX(您正在使用它)将创建一个单独的请求,并且只会到exit(); (这意味着它不会再次呈现HTML,因此不再显示带有它的新类。

可能最简单,最干净的方法是通过状态代码。

在PHP中设置不同状态代码的标题:

 if(strlen($username) < 5){
      echo '<span  class = "glyphicon glyphicon-remove" style = "color:red"> More then 4 caracters </span>';
      header('HTTP/1.1 406 Not Acceptable');
      exit();
 }

在您的JavaScript中添加另一个案例以成功回复:

    if (hr.readyState == 4){
        status.innerHTML = hr.responseText;
        if (hr.status == 200) {
            document.getElementById('submit').className = "btn btn-primary";
        } else {
            document.getElementById('submit').className = "btn btn-primary disabled";
        }
    }

答案 1 :(得分:1)

像@Rein Baarsma已经说过的那样,你所面临的问题清楚地突出了正确分离问题的必要性。

正在发生的事情是,由于表单,PHP文件和Javascript AJAX功能都在同一页面上,当您发出请求时,响应文本将返回整个页面,包括表单(可能还有您的javascript)代码)导致您正在目击的副本。

避免此问题的一种方法是将应用程序的各个部分分开。在此模型中,您至少有两个文件。但这需要对代码进行一些重新分解,就像目前的情况一样。见下面的例子:

我选择致电register-front.php的文件1将包含您的HTML和Javascript / AJAX代码:

<div class="form-group">
<label for="username" class="col-lg-2 control-label">Username:</label>
<div class="col-lg-10">
    <input type="text" name = "username" class="form-control" id="username" onkeyup="checkUsername()">
    <br>
    <div class = "userspan">
        <span style = "font-size:15px"id = "usernamestatus"></span>
    </div>
</div>
</div>
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" class="<?php echo $buttonClass ?>" id = "submit" >Submit</button>

<script type="text/javascript" language = "javascript">
function checkUsername () {
    var status = document.getElementById("usernamestatus");
    var u = document.getElementById("username").value;
    if(u != "") {
        status.innerHTML = 'Se verifica...';
        var hr = new XMLHttpRequest();
        hr.open("POST","register.php",true);
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        hr.onreadystatechange = function(){
            if(hr.readyState == 4 && hr.status == 200){
                var parsedReply = JSON.parse(hr.responseText);
                status.innerHTML = parsedReply.button;
                document.getElementById('submit').className = parsedReply.buttonClass;
            }
        }
        var v = "name="+u;
        hr.send(v);
    }
}
</script>

文件2,我称之为register-back.php将包含您的PHP代码:

<?php $buttonClass = 'btn btn-primary'; ?>

<?php

$msg = "{";

if(isset($_POST['name']) && $_POST['name'] != ""){
   $username = preg_replace('#[^a-z0-9]#i', '', $_POST['name']);
   $quer = "SELECT * FROM users WHERE username = '$username'";
   $resu = mysqli_query($dbc,$quer);
   $check = mysqli_num_rows($resu);
   if( strlen($username) < 5 ){
      $msg .= "'button' : '<span  class = \"glyphicon glyphicon-remove\" style = \"color:red\"> More then 4 caracters </span>', 'buttonClass':'btn btn-primary disabled'";
   } 
   elseif( is_numeric($username[0]) ) {
      $msg .= "'button' : '<span  class = \"glyphicon glyphicon-remove\" style = \"color:red\"> First character mst be a letter </span>', 'buttonClass':btn btn-primary disabled'";
   }
   elseif($check < 1){
      $msg .= "'button':'<span class = \"glyphicon glyphicon-ok\" style = \"color:green\"> ' . $username . ' is available</span>', 'buttonClass':''";
   }else{
      $msg .= "'button': '<span  class = \"glyphicon glyphicon-remove\" style = \"color:red\"> This username is already taken </span>', 'buttonClass':'btn btn-primary disabled'";
   }

   $msg .= "}";

   header("Content-Type: application/json");
   echo $msg; 
   exit;
}
?>