开发者

How to update Ajax call (not content)

Look at this code please - how could I kill / update or restart an ajax call (not content that Ajax calls) after the content has already been called?

I mean the $('#posting_main') is called onclick and animated - how to stop ajax and make it another $('#p开发者_开发百科osting_main') on another click?

 $(document).ready(function() {

 $("#img_x_ok").click(function(e){
 e.preventDefault();

 var post_text = $.trim($("#main_text_area").val());

 var data_text = 'post_text='+ post_text;
 if (post_text === "") return;

 var xhr = $.ajax({

 type: "POST",
 url: "comm_main_post.php",
 data: data_text,
 cache: false,

 success: function (data){
 //content

 $("#posting_main").fadeIn();
 $("#posting_main").load("pull_comm.php");
 $("#main_text_area").attr("value", "");

 $("#posting_main").animate({ 
     marginTop: "+=130px",
 }, 1000 );

 }

 }); //ajax close

 }); }); //both functions close


You can abort the current request with:

xhr.abort();

After having done that, you can run another $.ajax(...) to make a second request.


You could implement it like the following. Note that indenting code makes it a lot more readable!

 $(document).ready(function() {

     var xhr; // by placing it outside the click handler, you don't create
              // a new xhr each time. Rather, you can access the previous xhr
              // and overwrite it this way

     $("#img_x_ok").click(function(e){

         e.preventDefault();

         var post_text = $.trim($("#main_text_area").val());

         var data_text = 'post_text='+ post_text;
         if (post_text === "") return;

         if(xhr) xhr.abort(); // abort current xhr if there is one

         xhr = $.ajax({

             type: "POST",
             url: "comm_main_post.php",
             data: data_text,
             cache: false,

             success: function (data){
                 //content

                 $("#posting_main").fadeIn();
                 $("#posting_main").load("pull_comm.php");
                 $("#main_text_area").attr("value", "");

                 $("#posting_main").animate({ 
                     marginTop: "+=130px",
                 }, 1000 );

             }

         });

     });

});


I am not sure I fully understand your question, however:

  1. xhr.abort() will kill the AJAX request. After calling abort(), you could modify and resend the request, if desired.
  2. $("#posting_main").stop() will stop the fadeIn animation. (And I think you might need to follow that with $("#posting_main").hide() to be sure it isn't left partially visible.)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜