简体   繁体   English

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

[英]Ajax codeigniter, loading too fast on success. .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. 现在我只用了不到一周的时间就尝试使用Ajax与codeigniter来创建一个相当复杂的ajax菜单系统。 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. 我将ajax代码发布到数据库中,并成功将其添加到菜单系统中。 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. 如果我稍等片刻,然后使用附加在ajax调用中的按钮而不是使用.done手动进行调用,则效果很好。

This is my ajax call 这是我的ajax电话

// 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";
                    } 

                }

            ?>

Ajax Deferred 阿贾克斯

If you wanted to use the ajax deferred method, you would do something like this. 如果要使用ajax延迟方法,则可以执行以下操作。

(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));

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

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