从控制器JSON传递值以查看CodeIgniter中的Ajax

myn*_*ohn 1 php ajax jquery json codeigniter

问题是我得到的对话框为false但查询运行正常并且值已成功添加到数据库中.它应该打印成真,但它给了我一个假的.我通过Firebug检查了值res = 1,但我不知道它有什么问题.

我的看法:

$.ajax({
    url: "<?php echo site_url('itemsController/additems'); ?>",
    type: 'POST',
    data: form_data,
    success: function(msg) {
        if(msg.res == 1)
        {
            alert(true);
        }
        else
        {
            alert(false);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

控制器:

        $result = array();
        $this->load->model('itemsModel');
        $query = $this->itemsModel->addItemstoDB($data);

        if ($query){  //&& any other condition
            $result['res'] = 1;
        }
        else
        {
            $result['res'] = 0;
        }
        echo json_encode($result); //At the end of the function.
    }
}
Run Code Online (Sandbox Code Playgroud)

azi*_*ani 5

尝试将您设置dataType为,json以便从服务器发回的数据被解析为JSON.

$.ajax({
    url: "<?php echo site_url('itemsController/additems'); ?>",
    type: 'POST',
    data: form_data,
    dataType: 'json',
    success: function(msg) {
        if(msg.res == 1) {
            alert(true);
        }
        else
        {
            alert(false);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)