此代码不会显示任何结果。我想将一个变量从ajax传递给控制器,然后从模型中找到值并将其传递给ajax;我希望在代码中显示一条消息。
查看 - test_view.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btnclick").click(function(){
var cname=$("#txt_uname").val();
//alert(cname);
$.ajax({
type:"post",
url:"http://localhost/NPOS/test/nameget",
data:{txt_uname : cname},
success:function(data){
if(data==0){
$("#message").html("<font color='#55DF00'>Name Available</font>");
}
else{
$("#message").html("<font color='#FF0000' >Name Already taken</font>");
}
}
});
});
});
</script>
<input type="text" name="txt_uname" id="txt_uname"/>
<input name="btnclick" type="button" id="btnclick" value="Search">
Controller - test.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller {
public function index()
{
$this->load->view('test_view');
}
function nameget()
{ $this->load->model('test_model');
$name= $this->input->post('txt_uname');
$find=$this->test_model->nameget($name);
}
}
?>
model - test_model.php
class Test_Model extends CI_Model
{
function nameget($name)
{
$query=$this->db->query("SELECT * from countries where country_name='$name'");
return $query->result();
}
}
答案 0 :(得分:1)
使用此Ajax代码
<script type="text/javascript">
$(document).ready(function(){
$("#btnclick").click(function(){
var cname=$("#txt_uname").val();
//alert(cname);
$.ajax({
type:"post",
url:"<?php echo base_url() ?>test/nameget",
data:{txt_uname : cname},
success:function(data){
if(data==0){
$("#message").html("<font color='#55DF00'>Name Available</font>");
}
else{
$("#message").html("<font color='#FF0000' >Name Already taken</font>");
}
}
});
});
});
</script>
数据发送和网址已更改
Opz忘了这个
在模型中
function nameget($name)
{
$query=$this->db->query("SELECT * from countries where country_name='$name'");
$result = $query->result_array();
return $result;
}
答案 1 :(得分:0)
在ajax代码的标题中使用它:
$(document).ready(function(){
$("#btnclick").click(function(){
var BASE_PATH='<?php echo base_url() ?>';
var cname=$("#txt_uname").val();
$.post(BASE_PATH+"test/nameget",{txt_uname:cname},function(data){
if(data==1){
$("#message").html("<font color='#FF0000' >Name Already taken</font>");
}else{
$("#message").html("<font color='#55DF00' >Name Available</font>");
}
});
});
});
在控制器中添加此功能
//Function in controller for call model function and return the response
function nameget(){
$this->load->model('test_model');
$txt_uname=$this->input->post('txt_uname');
$check_availablity=$this->test_model->nameget($txt_uname);
if($check_availablity==TRUE){
echo 1;
}else{
echo 0;
}
}
在模型中添加以下功能:
//Function in model for fetch data from table
function nameget($txt_uname=''){
if($txt_uname=='')
return false;
$this->db->select('*');
$this->db->from('countries');
$this->db->where(array('country_name'=>$txt_uname));
$recordSet = $this->db->get();
$data=$recordSet->result() ;
if(count($data)>0)
{
return true;
}else
{
return false;
}
}