[英]jquery ajax call not giving response in codeigniter
我第一次嘗試在codeigniter中使用jquery ajax。 我沒有收到來自ajax調用的任何響應。 當我單擊按鈕時,我可以使用j.ajax之前的警報來驗證數據,但不會響應實際的ajax調用。 請協助尋找問題。
我的看法是:
<!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;
}
}
?>
親愛的朋友:您使用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;
}
}
?>
只需將ajax調用中的POST更改為GET即可,因為您正在使用get方法來接收變量。如果您的click函數正常運行,我嘗試了您的代碼,那么通過進行此小更改便可以正常工作:-
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);
}
});
});
您是否注意到使用j進行jquery卻使用$ .ajax進行ajax調用?
請在控制器中使用
error_reporting(0);
header('content-type:application / json; charset = utf-8');
header('Access-Control-Allow-Origin:*');
header(“ Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept”);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.