[英]AJAX response is not returning in codeigniter
I am new in codeigniter. 我是Codeigniter的新手。 I am writing a code.
我正在编写代码。 AJAX response is not returning.
AJAX响应未返回。
Here is my controller: 这是我的控制器:
public function getValue()
{
$this->load->helper('url');
$data = array(
'username' => $this->input->post('username'),
'email'=>$this->input->post('email'),
'address'=>$this->input->post('address')
);
echo json_encode($data);
die;
}
and it is view code: 它是查看代码:
$( document ).ready(function() {
$('#btn_submit').on("click", function(event){
event.preventDefault();
var username = $('#username').val();
var email = $('#email').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/MyApp/getValue",
dataType: 'json',
async:true,
crossDomain:true,
data: {username: username, email: email, address: address},
success: function ( data) {
console.log(data);
},
error: function ( data ) {
console.log('error');
}
});
});
});
I am new with codeigniter, so I don't know how to return response and work with AJAX. 我是Codeigniter的新手,所以我不知道如何返回响应并使用AJAX。 I have coded with the help of web but still getting errors.
我已经借助网络进行了编码,但是仍然出现错误。 Please guide me how to fix this.
请指导我如何解决此问题。 Thanks
谢谢
Simple answer remove die;
简单的答案删除
die;
from the getValue()
function. 从
getValue()
函数。
Codeigniter does not actually output anything until after the controller finishes execution. 直到控制器完成执行后,Codeigniter才实际输出任何内容。 The call to
die;
die;
的呼唤die;
short circuits the normal operation of the framework and so nothing gets output. 短路了框架的正常运行,因此没有任何输出。 In other words,
echo json_encode($data);
换句话说,
echo json_encode($data);
never actually happens. 从来没有真正发生过。
Please try after setting content-type for the response like below. 请为以下响应设置内容类型后尝试。
header('Content-Type: application/json');
echo json_encode($data);
die;
Ajax response expects json data since your code set dataType: 'json'
由于您的代码设置了
dataType: 'json'
Ajax响应需要json数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.