通过ajax请求将会话变量与post变量进行比较

时间:2016-08-23 10:14:47

标签: ajax session post

我希望当验证码从用户完成发送到页面的请求并将用户的输入字符串与验证码图像的值进行比较(此值存储在会话值中)

这是包含ajax请求的页面(这里不是img标签,但它并不重要!):

<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input id="captcha" maxlength="5" onkeyup="myFunction()" value="">
<script>
function myFunction() {
    var x = document.getElementById("captcha"); 
    if(x.value.length==5){
      $(document).ready(function(){
        $.get("test.php",
          function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
          });
        });
    }
}
</script>
</body>
</html>

此页面是获取帖子请求:

<?php
session_start();
$c=$_POST['captcha']; echo $c;echo gettype($c);
$s=$_SESSION['captcha']; echo $s;echo gettype($s);
if($c==$s) {
    echo 'correct';
} else {
    echo 'incorrect';
}
?>

但作为回应:会话变量的类型是NULL!为什么呢?!

但是post变量的类型是字符串,但我确定session和post是相等的。

现在如何比较?

1 个答案:

答案 0 :(得分:0)

这个问题解决了!但我不确切!

我在serach ajax工作,当然还要开始会议。

但在工作之前和之后都没有问题。

但我觉得更好的是在页面上发送请求,会话开始。

它有效!

然后我删除了session_start()语句,但它仍然有效:D

我觉得代码没有心情:))

页面代码发送请求:

<html dir="rtl">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="captcha" src="captcha.php" width="160" height="45" border="1" alt="CAPTCHA">
<small><a href="#" onclick="
document.getElementById('captcha').src = 'captcha.php?' + Math.random();
document.getElementById('captcha_code').value = '';
return false;
">refresh</a></small>
<input id="fname" type="text" name="captcha" size="6" maxlength="5" onkeyup="myFunction()" value="">
<small id="massage-captcha">input number show on the image.</small>
<script>
function myFunction() {
var x = document.getElementById("fname"); 
if(x.value.length==5){
    document.getElementById("massage-captcha").innerHTML = "please wait!";
    $(document).ready(function(){
        $.post("test.php",
        { 
        captcha: x.value
        },
        function(data,status){
            if(data=="correct"){
                document.getElementById("massage-captcha").innerHTML = "correct";}else{
                document.getElementById("massage-captcha").innerHTML = "incorrect";
            }
        });
    });
}
else{
    b.value="";
}

}
</script>

和文件recive请求:

<?php
session_start();
if($_POST['captcha']==$_SESSION['captcha']){echo 'correct';}
else{echo 'incorrect';}
?>

我的最后一个想法:服务器上的会话在过去的一天之后删除,现在工作正常!

相关问题