【问题标题】:Deleting of Data on the fly not working动态删除数据不起作用
【发布时间】:2011-09-01 04:02:44
【问题描述】:

我正在尝试使用 jquery ajax 来删除某些特定于配方成分的数据,并且我正在使用 CodeIgniter 框架,但它失败了。这是我的代码部分:

$(".delete").live('click',function()
{
 var ri_id = $(this).attr('id');
 if(confirm("Are you sure you want to delete this ingredient? Action cannot be undone."))
 { 
  var r_id = "<?php echo $this->uri->segment(3); ?>";
  alert(ri_id +" " +r_id); 
  $.ajax({
     type: "POST",
     url: "/ingredient/delete",
     data: "ri_id="+ri_id +"&r_id=" +r_id,
     success: function(){
      $(this).parent().parent().parent().remove();
     },
     failure : alert('fail')
  });

那么这里是我的配料.php:

class Ingredient extends CI_Controller {

    function delete()
    {
        $data['ri_id']= $this->input->post('ri_id');
        $data['r_id']= $this->input->post('r_id');

        if (!empty($data['id']))
        {
            $this->load->model('ingredient_model', '', TRUE);
            $this->ingredient_model->delete_recipe_ingr($data);
            $this->output->set_output('works');
        } 
        else 
        {
            $this->output->set_output('dontwork');
        }
    }

}

还有我的模特:

  class Recipe_model extends CI_Model
  {
      public function delete_recipe_ingr($data)
      {
          $this->db->where($data);
          $this->db->delete('st_recipe_ingredients');  
      } 
  }

是我遗漏了什么还是我的代码有误?我将衷心感谢您的帮助。提前致谢。

【问题讨论】:

  • 不执行成功部分,只执行失败部分。没有控制台错误。我可以看到显示“失败”的警告框。
  • 我想你的意思是error: function(xhr, status, error) { alert(error) },没有failure选项,说failure: alert('fail')会立即执行alert()
  • 我明白了。感谢那。我没有错误,但我尝试删除的数据仍然无法正常执行。 :(
  • .ajax() 部分中的类型、url 和数据是否正确?

标签: php jquery ajax codeigniter


【解决方案1】:

我的第一个猜测是 this 并不是你认为的那样:

success: function(){
  $(this).parent().parent().parent().remove();
},

来自fine manual

上下文
该对象将成为所有与 Ajax 相关的回调的上下文。默认情况下,context 是一个表示调用中使用的 ajax 设置的对象($.ajaxSettings 与传递给 $.ajax 的设置合并)。

所以在你的 success 回调中,this 几乎是一个简单的对象,而不是 DOM 中的东西。

有两种标准解决方案。您可以保存对this 的引用并使用它:

var self = this;
$.ajax({
    // ...
    success: function() {
        $(self).parent().parent().parent().remove();
    },
    // ...

或使用context 选项到$.ajax

$.ajax({
    // ...
    context: this,
    success: function() {
        $(this).parent().parent().parent().remove();
    },
    // ...

当然,还要修复 cmets 中讨论的 failure 内容。

【讨论】:

  • 我明白了。然后我将删除的行会消失,它会进入成功部分,但是当我刷新页面时。数据还在。这是它们只是在页面上而不是在数据库中被删除。我的类型、url 和数据中的参数是否正确?我有机会检查我传递给控制器​​的东西吗?还是我在网址上指定的路径正确?对不起,这是我第一次做这样的事情。请多多包涵。 :(
  • @Jagad:我不确定 PHP 方面的事情,抱歉。我更新了您问题的标签,希望有人能来帮助您解决问题的另一半。
  • 我现在明白了。 :) 谢谢。我只需要修复我的控制器和模型中的脚本。
  • @Jagad:很酷,很高兴即使对 CodeIgniter 一无所知,我也能提供帮助。
猜你喜欢
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2017-08-30
  • 2011-04-13
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多