简体   繁体   中英

Load two divs with a single AJAX call

I'm trying to use load() to load two divs #follow-x and #follow-y ajaxly with a click of a button.This is what I have tried in success function,but doesn't work,but works if I remove one of the function,so it loads only one div but I want it to load both.Thanks in advance

$('#follow').click(function(){

          $.ajax({

                   type: "POST",
                   url: "{% url 'follow_class' %}",
                   data: {'pk': '{{class.pk}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                   dataType: "json",
                   success: function(){
                       $('#follow-x').load("{% url 'class_details' %} #follow-x");}
                       function(){
                       $('#follow-y').load("{% url 'class_details' %} #follow-y");}

              }); 
        });
</script>

Dont mind the tags {} I'm using Django

only the first function is being called on success

put both statements in one function

$('#follow').click(function(){

          $.ajax({

                   type: "POST",
                   url: "{% url 'follow_class' %}",
                   data: {'pk': '{{class.pk}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                   dataType: "json",
                   success: function(){
                       $('#follow-x').load("{% url 'class_details' %} #follow-x");                        
                       $('#follow-y').load("{% url 'class_details' %} #follow-y");
                    }

              }); 
        });

Your second load call is in another function that never gets called

$('#follow').click(function(){

          $.ajax({

                   type: "POST",
                   url: "{% url 'follow_class' %}",
                   data: {'pk': '{{class.pk}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                   dataType: "json",
                   success: function(){
                       $('#follow-x').load("{% url 'class_details' %} #follow-x");
                       $('#follow-y').load("{% url 'class_details' %} #follow-y");
                   }

              }); 
        });
</script>

Success is a property of the object passed to AJAX. In your code you attempt to assign it to a function containing the follow-x code, however a syntax error is produced due to the next function statement that violates the obj structure. Try this.

success: function(){
     $('#follow-x').load("{% url 'class_details' %} #follow-x");
     $('#follow-y').load("{% url 'class_details' %} #follow-y");
}

Also consider using the done callback instead of success. More info on that here what is difference between success and .done() method of $.ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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