2017-02-24 95 views
-1

我正在嘗試第一次在codeigniter中使用jquery ajax。我沒有收到任何來自Ajax電話的迴應。當我點擊按鈕時,我可以在j.ajax之前使用警報來驗證數據,但對實際的ajax調用沒有響應。請幫助找到問題。jquery ajax調用沒有在codeigniter中提供響應

我的看法是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<script src="<?php echo base_url(); ?>js/jquery-latest.js" type="text/javascript"></script> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
</head> 
<body> 
<script type="text/javascript"> 
var j=jQuery.noConflict(); 
j(document).ready(function(){ 
    j("#b").click(function(){ 
     var scode=j("#a").val(); 
     var baseurl="<?php echo base_url(); ?>"; 
     $.ajax({ 
     type: 'POST', 
     url: baseurl + 'ajax/aj', 
     data: {txt:scode}, 
     success:function(response){ 
      j("#c").val(response); 
     } 
    }); 
    }); 
}); 
</script> 
<form id="form1" name="form1" method="post" action=""> 
    <label for="a"></label> 
    <input type="text" name="a" id="a" /> 
    <input name="b" type="button" value="click" id="b" /> 
    <input type="text" name="c" id="c" /> 
</form> 
</body> 
</html> 

我的控制器:

<?php 
class ajax Extends CI_Controller{ 
    public function __construct() 
    { 
    parent::__construct(); 
    $this->load->helper('url'); 
    } 
    public function index(){ 
     $this->load->view('ajax_trial'); 
    } 
    public function aj(){ 
     $x=$this->input->get('txt'); 
     echo $x; 
    } 
} 
?> 
+0

你得到的控制器'$ x'什麼價值? –

+0

我不使用模型 – Amit

+0

嘗試在控制檯中進行調試。 – DevOps

回答

0

只要改變POST的AJAX調用來獲取爲u使用GET方法來接收變量。我想你的代碼如果你的點擊功能正在工作,那麼通過做這個小改變它將工作: -

jQuery("#b").click(function(){ 
      var scode=jQuery("#a").val(); 
      var baseurl="<?php echo base_url(); ?>"; 
      jQuery.ajax({ 
       type: 'GET', 
       url: baseurl + 'test/aj', 
       data: {txt:scode}, 
       success:function(response){ 
        console.log(response); 
        jQuery("#c").val(response); 
       } 
      }); 
     }); 
0

你有沒有注意到你ar使用J的jQuery,但使用$ .ajax的Ajax調用?

+0

我試圖通過更改j $ $ butconsole給出此錯誤
XMLHttpRequest無法加載http:// [:: 1]/ebizport/ajax/aj?txt = aa。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許Origin'http:// localhost'訪問。 – Amit

0

請使用此控制器

error_reporting(0);

header('content-type:application/json; charset = utf-8');

header('Access-Control-Allow-Origin:*'); (「Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept」);

2

親愛的朋友,您使用POST方法發送數據,並使用你get方法,你必須使用POST方法打印數據....

<?php 
class ajax Extends CI_Controller{ 
    public function __construct() 
    { 
    parent::__construct(); 
    $this->load->helper('url'); 
    } 
    public function index(){ 
     $this->load->view('ajax_trial'); 
    } 
    public function aj(){ 
     $x=$this->input->post('txt'); 
     echo $x; 
    } 
} 
?>