我想在用户插入用户名&密码。我正在使用像这样的表单字段提交返回相同的功能而不是刷新。 onsubmit="return login();
查看
<?php $this->load->view('header');?>
<body>
<nav class="navbar navbar-default">
<div class="navbar-header">
<a href="#" class="navbar-brand">Store</a>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="panel panel-default login">
<div class="panel-heading">Sign In</div>
<div class="panel-body">
<form data-toggle="validator" role="form" method="POST" onsubmit="return login();">
<div class="form-group">
<label for="username">Username</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" name="username" id="username" placeholder="Username" required>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-star"></span></span>
<input type="password" class="form-control" id="password" placeholder="Password" required>
</div>
</div>
<div class="alert alert-danger text-center" style="display:none;" id="error">
<p>Invalid username or password !!</p>
</div>
<button type="submit" class="btn btn-lg btn-success btn-block" id="login"><span class="glyphicon glyphicon-lock frm-general"></span>Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="<?=base_url('assets/js/jQuery-2.1.4.min.js');?>"></script>
<script src="<?=base_url('assets/js/bootstrap.min.js');?>"></script>
<script src="<?=base_url('assets/js/validator.min.js');?>"></script>
<script src="<?=base_url('assets/js/view/login.js')?>"></script>
</body>
</html>
的Ajax
$(function(){
$('#login').submit(function(e){
var username = $('#username').val();
var password = $('#password').val();
URL_GET_ACCESS = BASE_URL+"Login_controller/login";
$.ajax({
url: URL_GET_ACCESS,
type: 'POST',
data: 'username='+username+'&password='+password;
}).done(function(ans){
console.log(resp);
if(ans === '0'){
$('#error').show().delay(2000).fadeOut();
}else if(ans === '1'){
window.location.href='<?php echo base_url() ?>home/';
}else{
window.location.href='<?php echo base_url() ?>home/';
}
});
});
return false;
});
答案 0 :(得分:0)
我认为问题在于提交正在被触发,并且正在将您带到表单操作定义的URL(在本例中为自身)。为了防止这种情况,请在启动提交功能后立即使用jQuery&#39; e.preventDefault();
。
我经常使用的另一个解决方案是不使用提交按钮,而只是将 span (<span id='iWillSubmit' class='iLookLikeAButton'>
)设置为按钮,然后附加提交功能到 span 元素上的.on('click')
。