简体   繁体   English

在CodeIgniter中使用AJAX删除帖子

[英]Delete a post using AJAX in CodeIgniter

New to CodeIgniter and trying to learn AJAX/jQuery as well. CodeIgniter的新手,也尝试学习AJAX / jQuery。 I followed CI's tutorial on creating News site. 我遵循了CI创建新闻网站的教程。 I then applied AJAX to have posts load every 5 seconds. 然后,我应用AJAX使帖子每5秒加载一次。 I'm now attempting to add a delete for specific posts. 我现在正尝试为特定帖子添加删除内容。 I'm able to delete a post, but it doesn't stay on the same page and remove that single post I deleted. 我可以删除帖子,但是它不会停留在同一页面上,而是删除我删除的那条帖子。 (Takes me to a blank page and I have to click back - but the post is then deleted). (将我带到一个空白页面,我必须单击返回-但该帖子随后被删除)。

Model: 模型:

    public function delete_news($id)
{
    $this->db->delete('news', array('id' => $id));
}

Controller: 控制器:

public function delete_news_ajax($id)
    {
        $data['news'] = $this->news_model->delete_news($id);
    }

View Script: 查看脚本:

function getNews(){
$.ajax({
    url: "<?php echo base_url(); ?>/index.php/news/get_news_ajax/" + timestamp,
    success: function(data) {
      articles = jQuery.parseJSON(data);
      jQuery.each(articles, function() {
        $("#newsfeed").prepend($("<div id='newspost'><h2>"
                + this.title + "</h2><p>" 
                + this.text + '</p><p><a href=<?php echo base_url(); ?>/index.php/news/view/' 
                + this.slug + ">View article</a><br><a class='delete' href=<?php echo base_url(); ?>/index.php/news/delete_news_ajax/" 
                + this.id + ">Delete</a></p></div>").fadeIn("slow"));
            timestamp = this.time;
      });
    }
});

} }

What am I doing wrong? 我究竟做错了什么? The page loads/refreshes posts just fine. 页面加载/刷新帖子就好了。 But I can't get the delete to work. 但是我无法执行删除操作。 Any help would be appreciated. 任何帮助,将不胜感激。

I guess the url is going to make a full redirect because it is a complete url that should make a full redirect nothing preventing it. 我猜该网址将进行完全重定向,因为它是一个完整的网址,应该进行完全重定向不会阻止它。 You might need an extra Jquery code. 您可能需要一个额外的Jquery代码。 This has nothing to do with Codeigniter. 这与Codeigniter无关。 Try something like this: 尝试这样的事情:

$(document).on("click", "#newsfeed .delete", function(event){
  event.preventDefault();
  var url = $(this).attr("href");
  $.get(url, function(data) {
  alert('Data Deleted Successfully');
});
  return false;
});

You could also use the preventDefault. 您也可以使用preventDefault。

The above code could need a little tweaking to fit your case. 上面的代码可能需要一些调整才能适合您的情况。 Couldn't test it since I don't have what your db is returning. 无法测试它,因为我没有您的数据库返回的内容。 Just try it and let me know what you get. 尝试一下,让我知道您得到了什么。

[EDIT] I have made changes to the code. [编辑]我对代码进行了更改。 Since .on replaces the deprecated .live, it should be able to detect new elements that are added to the page via ajax. 由于.on替换了不推荐使用的.live,因此它应该能够检测通过ajax添加到页面的新元素。 That way, the function should work if the element is properly targeted. 这样,如果适当地定位了元素,则该功能应该可以正常工作。 I also included the preventDefault just in case you need that. 我还包括了preventDefault,以防万一您需要它。 It should work like return false, which should prevent the anchor from redirecting the page. 它应像return false一样工作,这应防止锚点重定向页面。 I guess your target element has to be adjusted. 我想您的目标元素必须调整。 Bind .on to document as show in the edit above. 如上编辑所示,将.on绑定到文档。 Once this happens your page would not redirect except you have something else in the page that is breaking the javascript. 一旦发生这种情况,您的页面将无法重定向,除非页面中有其他损坏JavaScript的内容。 Use firefox to find this out. 使用firefox找出答案。

If that does not work, I'd have to recommend that you use the jquery livequery plugin Click Here . 如果还是不行,我必须建议您使用了jQuery的liveQuery插件点击这里 Check version for compatibility. 检查版本的兼容性。 Use Jquery migrate if using jquery 1.9 because .live id deprecated. 如果使用jquery 1.9,请使用Jquery migration,因为不建议使用.live id。 It does a good job in binding ajax added elements like yours. 在绑定像您这样的ajax添加元素方面,它做得很好。

For good reasons, this very code should work--just ensure that your targeting is correct. 出于充分的原因,此代码应该可以正常工作-只需确保您的定位正确即可。 If it doesn't, please use firebug in firefox and let me know what you get in your case. 如果不是,请在firefox中使用firebug,让我知道您的情况。

I hope this helps you. 我希望这可以帮助你。

I have a working solution. 我有一个可行的解决方案。 Issue seemed to be with binding things correctly to the DOM. 问题似乎在于将事物正确绑定到DOM。 Had to call in the help of a couple others to get this all working correctly. 不得不打电话给其他几个人,以使所有这些都正常工作。 But functions exactly how I had intended before. 但是功能完全符合我的预期。 An individual can delete a post, and it fades away slowly without having to refresh the page or bumping the page back up to the top. 个人可以删除帖子,并且帖子会逐渐消失,而无需刷新页面或将页面颠倒回到顶部。

Used the same Model from up above 从上方使用相同的模型

Controller: 控制器:

public function delete_news_ajax($id) {
    $data['status'] = $this->news_model->delete_news($id);
    echo json_encode($data);
}

View: 视图:

var timestamp = "";
var numN = 0;
var numD = 0;
var chart;
function getNews() {
    $.ajax({
        url: "<?php echo base_url(); ?>/index.php/news/get_news_ajax/" + timestamp,
        success: function(data) {
            articles = jQuery.parseJSON(data);
            numD = articles.numDelete;
            jQuery.each(articles.new , function() {
                numN++;
                output = "<div class='newspost' id='newspost" + this.id + "'>\n\
                    <h2>" + this.title + "</h2>\n\
                    <p>" + this.text + '</p>\n\
                    <p>\n\
                        <a href="<?php echo base_url(); ?>/index.php/news/view/"' + this.slug + ">View article</a>\n\
                        <br><a class='delete' href='#' onclick='return deletenews(" + this.id + ")'>" + "Delete</a>\n\
                    </p>\n\
                </div>"
                $(".newsfeed").prepend($(output).fadeIn("slow"));
                timestamp = this.time;
            });

            jQuery.each(articles.deleted, function() {
                $("#newspost" + this.id).fadeOut('slow', $("#newspost" + this.id).remove);
                if (this.deletetime > timestamp) {
                    timestamp = this.deletetime;
                }
            }); 
        }
    }); 
}
$(document).ready(function() {
    setInterval("getNews()", 1000);

});

function deletenews(postid) {
    //event.preventDefault();
    $.ajax({
        url: "<?php echo base_url(); ?>/index.php/news/delete_news_ajax/" + postid,
        success: function(data) {
            var status = jQuery.parseJSON(data);
        }
    });
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM