嗨,我目前正在学习 jQuery 中的 AJAX,现在我正在尝试在 codeigniter 中使用它。现在发生的事情是我有一个文本框,其中在 keyup 事件上它会调用我的控制器上的函数并且它仍然在工作,但是控制器本身没有获得文本框的当前值并且它保持空白,因为我没有提交表单尚未,因此无法获取 POST 数据。好吧,我也不想提交表单,因为我只有一次提交机会,而我只想检查事件是否已经存在(用于验证目的)。到目前为止,这是我的代码,添加了注释以便更好地查看。
看法:
<div>
<form>
<table border="0">
<tr>
<td>
<title>Name: </title>
</td>
<td>
<input id="name" type="text" name="eventname" />
</td>
<td>
<div id="name1"></div>
</td>
</tr>
</table>
<script type="text/javascript" src="<?php echo $base; ?>javascripts/jquery-1.8.2.min.js">
</script>
<script type="text/javascript" src="<?php echo $base; ?>javascripts/ajax.js">
</script>
</form>
</div>
控制器:
<?php
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('test_model');
}
public function view()
{
$data['base'] = $this->config->base_url();
//CHECK IF THE $PAGE VIEW IS EXISTING
if ( !file_exists('test/views/pages/test_form/test_form.php'))
{
// IF PAGE DOESN'T EXISTS SHOW 404 ERROR
show_404();
}
//FOR THE TITLE PART
$data['title'] = ucfirst('Test');
$this->load->view('templates/header', $data);
$this->load->view('pages/test_form/test_form', $data);
$this->load->view('templates/footer', $data);
}
public function message()
{
//this one will access database
echo $this->test_model->check_event($this->input->post('eventname'));
//username doesn't get the current value on keyup unlike the AJAX part
}
}
该模型:
<?php
class Test_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function check_event($test_input)
{
if($test_input==null){
return "True";
}
else
return "False";
}
}
和 AJAX:
$('#name').keyup(function() { //LISTENER FOR BUTTON CLICK BASED ON ID button ON THE PHP PAGE
var name = $('#name').val();
$.ajax({ //STARTS AJAX
type: 'POST',
url: '/CodeIgniter_2.1.3/index.php/login/message/', //THIS PAGE IS LOADED ON THE AJAX data IS THE CONTENTS ON THE PAGE NOTE COMMA SEPARATED VALUES
data: 'name='+name,
statusCode: { //THE STATUS FOR THE PAGE. NOTE THIS IS CASE SENSITIVE
404: function(){ //IF 404 ERROR OCCURS THIS MESSAGE WILL BE DISPLAYED
$('#name1').text('Page not found');
}, //NOTE COMMA SEPARATED VALUES
202: function(){ //IF 202 SHOW THIS TEXT
$('#name1').text('Please wait');
}
}, //NOTE COMMA SEPARATED VALUES
success: function(data){ //IF PAGE EXISTS OR FOUND THE data FROM THE GIVEN PAGE WILL BE LOADED AND PASSED
$('#name1').html(data); //THE content ID ON THE PHP PAGE WILL CONTAIN ALL THE html data OF THE GIVEN PAGE
}
});
});
很抱歉这个 AJAX 部分。它充满了我认为没有必要的评论。这只是我快速查看代码的注释。:) 我的代码有问题还是我需要使用某些功能来检索数据?