作为标题,我想将CI_Controller返回值/数据返回给AJAX,它之前发出请求。
The_Controller.php
class The_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
function postSomething()
{
$isHungry = true;
if(isHunry){
return true;
}else{
return false;
}
}
}
AJAX
(文档)$。就绪(()的函数 {
$('#form').on('submit', function (e)
{
e.preventDefault(); // prevent page reload
$.ajax ({
type : 'POST', // hide URL
url : '/index.php/The_Controller/postSomething',
data : $('#form').serialize (),
success : function (data)
{
if(data == true)
{
alert ('He is hungry');
}
else
{
alert ('He is not hungry');
}
}
, error: function(xhr, status, error)
{
alert(status+" "+error);
}
});
e.preventDefault();
return true;
});
});
问题:
上面的AJAX代码对于变量数据总是变为FALSE。它没有从CI_Controller中的postSomething函数获得返回值。
问题:
我想if(data == true)结果提醒('他饿了');.但是导致数据没有被CI_Controller中的postSomething函数的返回值填充,所以它总是为false。 如何从CI_Controller返回值/数据到AJAX?
谢谢
答案 0 :(得分:1)
您需要稍微更改一下代码。无需从控制器返回数据,只需echo true
或echo false
。希望你能得到你想要的结果。
答案 1 :(得分:1)
PHP代码中有拼写错误
if(isHunry){
应该是
if($isHungry){
此外,将数据返回到AJAX请求,您确实应该在标头中发送正确的内容类型。实施例
header('Content-Type: application/json');
print
或echo
数据,而不是return
,以及json_encode
:
echo json_encode($data);
所以你的postSomething
php函数应该是这样的:
$isHungry = true;
header('Content-Type: application/json');
echo json_encode($isHungry);