我已经被困在这个问题上两天了。我发现代码在没有刷新的情况下发布数据,但似乎如果它没有刷新,那么这些值实际上并没有保存到$ _SESSION超全局。
我的jquery代码:
$('.login_error').hide();
$('#sublogin').click(function(){
$('.login_error').hide();
var jusername = $('#loginusername').val();
var jpassword = $('#loginpassword').val();
if(jusername == ""){
$('label#username_error').show();
//return false;
}
if(jpassword == ""){
$('label#password_error').show();
return false;
}
var dataString = 'loginusername='+jusername+'&loginpassword='+jpassword;
$.post('login.php', dataString, function(data) {
$('#header').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500)
});
// return false
});
我的login.php代码:
<?php
//set the variables
$username = isset($_POST['loginusername'])? $_POST['loginusername']:'';
$password = isset($_POST['loginpassword'])? $_POST['loginpassword']:'';
$step = isset($_POST['step']) ? $_POST['step'] : '1';
if($step=='2'){
//validation is done in javascript
//if there are no errors
if(empty($loginErrors)){
//sanitizes data for use in query.
$username = trim(mysql_real_escape_string($username));
$password = md5(trim(mysql_real_escape_string($password)));
$query = "SELECT user_level, username, password FROM user WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die('query did not go through');
if($result!=false){
$query_row = mysql_fetch_assoc($result);
$_SESSION['user_level']=$query_row['user_level'];
$_SESSION['username']=$query_row['username'];
$_SESSION['password']=$query_row['password'];
}
}
}
if($step=='1'){
?>
<form class="login_fields" id="login_fields" name="login" method="POST">
<input type="hidden" name="step" value="2"/>
<div class="dtable">
<div class="dtr">
<span class="dtd">
<label name="name_label" for="username_box"> Username </label>
</span>
<span class="dtd">
<input type="text" id="loginusername" name="loginusername" maxlength="25" value=""/>
</span>
<span class="tdt">
<label for="username" id="username_error" class="login_error">Username field can not be blank</label>
</span>
</div>
<div class="dtr">
<span class="dtd">
<label name="pass_label" for="username_box"> Password </label>
</span>
<span class="dtd">
<input type="password" id="loginpassword" name="loginpassword" maxlength="20" value=""/>
</span>
<span class="tdt">
<label for="password" id="password_error" class="login_error">Password field can not be blank</label>
</span>
</div>
<div class="dtr">
<span class="dtd">
<input type="submit" name="sublogin" id="sublogin" value="login"/>
</span>
</div>
</div>
<div class="output" id="output" name="output">
</div>
</form>
<?php
}
?>
编辑:啊,我忘了提。 login.php包含在我的头文件中,我的头文件包含在我的index.php文件中,因此session_start应该级联。
编辑2:因此,如果我在jquery代码的最后一行附近设置返回false,则页面不会重新加载,这正是我想要的但是会话根本没有保存。任何人都能弄清楚我正在做什么错了?
答案 0 :(得分:2)
您应该在PHP脚本的顶部声明session_start();
,否则将无法记住SESSION数据!!