我想使用session(使用PHP + ajax)创建登录表单,我使用json从控制器发送用户名,但它不起作用。我不知道什么是错的,请帮助
这是控制器中的功能:
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
这是form_login.js文件:
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
某些错误是'未捕获的ReferenceError:未定义alertError'
答案 0 :(得分:0)
有一个id =&#39; alertError&#39 ;?的元素 这可能是解决方案:
$("#alertError").attr('data-text', string);
...
答案 1 :(得分:0)
基本上,@ serakfalcon上面说的是:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...