dongli2000 2014-11-17 10:52
浏览 33

Ajax codeigniter,成功加载太快。 .done

I have only been working with ajax for under a week now trying to use it with codeigniter to create a pretty complex ajax menu system. The user can add new sections to the menu system as they work on it. I have ajax code posting to the database and on success adding it to the menu system. The problem I am having is that the code is running before the update is made to the database. So instead of getting the new menu section I just get a copy of the latest menu before making the addition. If I wait a moment and make the call manually with a button I attached with the ajax call instead of using .done this works fine.

This is my ajax call

// this is attached to my form to add a menu section
$(function(){
$('#add_category_form').submit(function(evnt){
    evnt.preventDefault(); 
    var posting = $.post(base_url+"/menu/add_category", $("#add_category_form").serialize());
    posting.done(newCategory());
    });
//calls view to generate menu section

function newCategory(){
$.ajax({
    'url' : base_url + '/' + controller + '/new_category',
    'type' : 'POST', //

    'success' : function(data){ 
        var container = $('#testcontainer'); 
        if(data){
            container.html(data);
        }
    }
});              

}

// view
<?php
$count = count($menu)+1;
        $counter=0;
                foreach ($menu as $category) {
                    $counter++;
                    if ($count == $counter) {
                    echo "menu html goes here of last menu created";
                    } 

                }

            ?>
  • 写回答

1条回答 默认 最新

  • ds9567 2014-11-17 21:49
    关注

    Ajax Deferred

    If you wanted to use the ajax deferred method, you would do something like this.

    (function($){
    
       $('#add_category_form').submit(function( event ){
           event.preventDefault();
    
           var _data = this.serialize();
    
           doSomething( _data ).then(
                function( response ){},  // Success
                function( error, code){}   // Error
           );
       });
    
       var doSomething = function( data ){
           return $.ajax({
              url : base_url + "/menu/add_category",
              data : data,
              type : 'POST',
              dataType : 'html'
           }).promise();  
       };
    
    }(jQuery));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?