CodeIgniter AJAX:POST不工作,GET工作正常

时间:2012-03-10 03:56:56

标签: php jquery ajax codeigniter

摆弄CodeIgniter并尝试抓住它,因为我之前从未使用过AJAX。

出于某种原因,当我使用GET方法时,我的AJAX工作正常,但如果我将其切换到POST方法,它就会停止工作。

我的JS:

$(document).ready(function(){

    $('.love').click(function(event) {

        $.ajax({

            type: 'GET',
            url: base_url + '/ajax/love_forum_post',
            data: { post_id: 2, user_id: 1, ajax: 1 },

        });

        return false;

    });

});

我的控制器:

function love_forum_post()

{

    $post_id = $this->input->get('post_id');
    $user_id = $this->input->get('user_id');
    $is_ajax = $this->input->get('ajax');

    if ($is_ajax)

    {

        $this->load->model('forums_model');
        $this->forums_model->add_love($post_id, $user_id);

    }

    // If someone tries to access the AJAX function directly.

    else

    {

        redirect('', 'location');

    }

}

如果我将类型切换为' POST'在我的JS中,然后在$ this-> input-> post()的另一端抓住它,它不起作用。

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

我已在两种情况下测试了您的代码: 首先 - 没有csrf保护,我认为没有理由让你的代码无法正常运行。 为了能够更轻松地测试它,请附加$ .ajax调用以及成功响应。 像这样的东西

success: function(response) {
            alert(response);
            }

并添加对love_forum_post方法的回复。

echo print_r($this->input->post(), true);

这样可以让您清楚地了解方法中的内容。

在我的安装中一切正常。

第二种情况是使用csrf保护。 在这种情况下,为帖子对象添加新参数。

<?php if ($this->config->item('csrf_protection') === true) : ?>
            post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>'; 
<?php endif ?>

这会使CI接受来自此网址的帖子。

希望它会有所帮助。 干杯

答案 1 :(得分:1)

你有没有启用csrf_protection?

如果是,您需要将令牌和值键作为post参数与post请求一起发送。

答案 2 :(得分:0)

尝试使用此

$post_data = $_POST;

并使用此

打印发布数据
print_r($post_data);die();

如果你抓住帖子数据就可以看到;

Gudluck !!

相关问题