编码器将一个变量从ajax发送到控制器


codeigniter sending a variable from ajax to controller

我目前正在做一个ajax添加,更新和删除。我想我就从删除开始吧,因为这是最简单的,希望它能对我的其他问题有所帮助。

在jquery中(在$doc中)。就绪,事件被正确触发)

if ($a == "Delete") 
{
    var postid = $(this).next('.postid').val();
    $(this).closest(".todo-content").fadeOut();
    jQuery.ajax({
        type: "POST",
        dataType: 'json',
        url: "<?=base_url()?>.index.php/classes/deletepost",
        data: {postid: postid},         
        async: false,
  });
}
在html

<form method="post">
    <button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
    <input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
在控制器

public function deletepost(){
        $id = $this->input->post('postid');
        $data = array('active' => 0);
        $this->Model_name->deletepost($id,$data);
        redirect('/abc/123');
    }

这是已经工作,但然后我计划使ajax的crud。我正试图将postid从ajax传递到控制器以删除此帖子。fadeout已经工作,但只有ajax没有。我是ajax的新手,所以我不知道我在哪里出错了,我也可能会再次问关于crud的其他部分的问题。

修复!

问题是$.ajax内部的url。它返回一个垃圾。

所以我在header 中添加了一个脚本
<script type="text/javascript">
    var BASE_URL = "<?php echo base_url();?>";
</script>
url:中使用BASE_URL就像url: BASE_URL+'classes/deletepost',

请尝试如下:

Codeigniters View:

<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
    <button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>

    <!-- Store ID and baseurl as attributes . this would help you to fetch data -->
    <button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
    <!-- reading jquery file .. -->
    <script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
    <!--you can write file in extra js file .. it depends on you -->
    <script type="text/javascript">
    $('#button').click(function(){
    // ask for confirmation
    var result = confirm("Want to delete?");
    // if it is confirmed
    if (result) {
    // get baseURL and ID using attributes
    var base_url = $('#button').attr('baseUrl');
    var postid  = $('#button').attr('postId');
    // make a ajax request
    $.ajax({
    url: base_url,
    type: "POST",
    dataType: 'json',
    success: function (data) {
        if(data){
                // Fade out the content id
                $('#content_id').closest(".todo-content").fadeOut();
        }       
    }
    });

    }
    });
    </script>
在控制器:

// You just need to delete the post and return a status code of "200"
public function deletepost(){
        $id = $this->input->post('postid');
        $data = array('active' => 0);
        $this->Model_name->deletepost($id,$data);
        redirect('/abc/123');
    }