1

我正在尝试实现一些相对简单的事情 - 允许用户在视图页面上发表评论,更新数据库并在页面上动态显示新内容,而无需刷新整个页面。

到目前为止,我的努力没有成功——我正在做的事情可能有几个问题!

在视图页面上,我尝试了这个(将 2 个变量发送到 CI 控制器函数):

<script type="text/javascript">
function ajax(id, user_id) {
jQuery('#dynamicdiv').load('/controller/function/' + id + '/' + user_id);
}
</script>

<div id='dynamicdiv'>
</div>

我有一个 textarea 来收集用户评论,在控制器功能中我应该能够将其称为发布数据以便将其写入数据库吗?如果是这样,我仍然需要将另外两个变量($id 和 $user_id)发送到 ajax 函数。

<?php $atts = array (
  'class' => "alignright button",
  'onClick' => "ajax('$id,$user_id')",
  ); ?>
<?php echo anchor(current_url(), 'Post my Comment', $atts); ?>

在控制器中,它涉及与我希望用户停留的页面不同的功能(视图):

$data = $this->model->database_query($id, $user_id);

echo $data; // from reading other posts it seems I would process the data within this function, to have it displayed on the page the user is viewing?

任何帮助表示赞赏!

4

2 回答 2

1

不要忘记阻止您的默认锚点行为(例如通过添加return false;到您的onclick参数)。

<?php $atts = array (
'class' => "alignright button",
'onClick' => "ajax('$id,$user_id'); return false;",
); ?>
于 2012-12-09T01:57:44.270 回答
0

您可以按如下方式发出 ajax 请求:

function ajax(id, user_id) {
    $.ajax({
        url: base_url + controller_name + '/' + action_name,
        type: 'GET',
        data: { id: id, user_id: user_id },
        dataType: 'json',
        success: function (data) {
            // append the returned result to your #dynamicdiv
        }
    });
}

在控制器中:

$id = $this->input->get('id');
$user_id = $this->input->get('user_id');

$data = $this->model->database_query($id, $user_id);
echo json_encode($data);

希望这可以帮助

于 2012-12-09T17:33:57.780 回答