我基本上是将表单值提交给我的控制器,而我正在使用CodeIgniter Framework。但是,当我将值发送到我的控制器的函数时,页面将更改为控制器并离开index.php(当前页面)
的index.php:
<form action="<?php echo base_url();?>index.php/LoginController/loginuser" method="post">
<input id="login_emailbox" name="login_emailbox" type="text" class="form-control welcome-login-email" placeholder="Email" required="">
<input id="login_passbox" name="login_passbox" type="password" class="form-control welcome-login-password" placeholder="Password" required="">
<button id="loginbtn" type="submit" class="btn btn-info" style="margin-left: 30px">Login</button>
</form>
LoginController.php:
class LoginController extends CI_Controller {
public function __construct()
{
parent::__construct();
}
function index()
{
$this->load->helper('html');
$this->load->helper('url');
$this->load->view('header');
$this->load->view('footer');
$this->load->view('index.php');
}
public function loginuser(){
echo $_POST['login_emailbox'];
echo $_POST['login_passbox'];
}
}
我在运行时采取的步骤:
1)我浏览到index.php via =&gt; http://localhost/codeig/index.php/LoginController/index
2)填写表格并点击提交。值将提交给函数: loginuser
3)页面被重定向到'loginuser'函数
如何避免这种情况并基本上将值发送到控制器中的loginuser函数而不刷新当前页面?
答案 0 :(得分:5)
<form action="" method="post" id="myForm">
<input id="login_emailbox" name="login_emailbox" type="text" class="form-control welcome-login-email" placeholder="Email" required="">
<input id="login_passbox" name="login_passbox" type="password" class="form-control welcome-login-password" placeholder="Password" required="">
<button id="loginbtn" type="submit" class="btn btn-info" style="margin-left: 30px">Login</button>
</form>
你的Jquery
$('#loginbtn').on('click',function(e){
e.preventDefault();
var data = $('#myForm').serialize();
var base_url='<?php echo base_url(); ?>'
$.ajax({
url:base_url+'index.php/LoginController/loginuser',
type:'POST',
data:data,
success:function(data){
alert(data); // here what you want to do with response
}
});
return false;
});
答案 1 :(得分:-1)
<form>
<input id="login_emailbox" name="login_emailbox" type="text" class="form-control welcome-login-email" placeholder="Email" required="">
<input id="login_passbox" name="login_passbox" type="password" class="form-control welcome-login-password" placeholder="Password" required="">
<button id="loginbtn" type="submit" class="btn btn-info" style="margin-left: 30px">Login</button>
</form>
<script>
$(document).ready(function(){
$('#loginbtn').click(function(){
var login_emailbox = document.getElementById('login_emailbox').value;
$.ajax({
url:'<?=base_url()?>index.php/Controller/function',
method: 'post',
data: {login_emailbox: login_emailbox},
dataType: 'json',
success: function(response){
alert('data updated');
}
});
});
});
</script>