Codeigniter返回带有空变量的视图


Codeigniter returns view with null variable

当我从另一个形式的数据,当我测试它在打印($id)它的工作,但当我传递它在视图中,当视图加载,它返回为空。

下面是我的代码:

Jquery发布

function viewAccount(orId)
{
    account_id=orId;
    // alert(account_id);
    var postData={
        "id":account_id
    };
    $.post(base_url+"admin/viewAccount", postData).done(function(data){
        inlcudeViews('admin/viewAccount');
    });
}

控制器:

function viewAccount()
{
    $id = $this->input->post('id');
    $data =  array('id' => $id);
    // print_r($data); IT WORKS TILL HERE
    $this->load->view('admin/viewAccount', $data);
}

视图:

// HERE IS WHERE I GET A NULL VARIABLE
var data='<?= $id ?>';
$(document).ready(function() {
    alert(data);
});

与其在viewAccount视图中使用alert,你只需要在$id视图中使用printecho

<?php
   echo isset($id) ? $id : '';
?>

另外,验证您已经在php.ini中启用了PHP短标记。如果使用<?= $id ?>

你的Jquery和View是完美的。但是在Controller中你必须写

$this->load->view('admin/viewAccount', $data[0]);

代替

$this->load->view('admin/viewAccount', $data);

或者写

function viewAccount()
{
    $id = $this->input->post('id');
    $data['id'] =$id;
    // print_r($data); IT WORKS TILL HERE
    $this->load->view('admin/viewAccount', $data);
}

您需要像下面这样将id传递到data array

控制器

$id = $this->input->post('id');
$data['id']=$id;
//print_r($data); IT WORKS TILL HERE
$this->load->view('admin/viewAccount', $data);

javascript中没有echo $id,应该是echo $id:

此处更新:

// HERE IS WHERE I GET A NULL VARIABLE
var data='<?php echo $id; ?>';
    $(document).ready(function() {
        alert(data);
    });

感谢您的快速回复,上面的答案都不起作用。我设法找到了一个解决方案,但它完全不同的方法,我只是把id作为一个全局变量。但是我仍然对这个问题的答案很感兴趣,我想这会对其他人有帮助。