简体   繁体   中英

Run JS Function on Ajax Success & on Page Load

I have a function newCount that I run on Ajax success and it is working OK, however, I want to also run the same function every time the window is reloaded but for some reason I'm unable to call the function with newCount();

my code:

.ajax

$( document ).ajaxComplete(function() {
    newCount();
});

.js

function newCount() {

    var sum = 0;
    $('.myclass').each(function() {
        sum += parseFloat($(this).text());
    });
    // update count in html
    $('#myid').html(sum);

}; // end count function

newCount(); // ajax not working when this in place

when I add newCount(); after the function, it will run correctly on page load, but the ajax will no longer work and vice versa.

What am I missing? How can I call the same function from the ajax success and every time the page is loaded?

Hey I've created this Plunker to show you how you should call the functions. Here is the Javascript code.

<script>
    (function(){
      function newCount(msg) {
        alert("message from: " + msg);
      }; // end count function
      debugger;
      newCount("Page load");
      $.get( "data.json", function( data ) {
        alert( "Load was performed." );
      });

      $(document).ajaxComplete(function() {
        newCount("ajax complete");
      });
    })();

EDIT 1 I've changed the Plunker so you can see that also works inside the $.ajax success property.

  $.ajax({
    url: "data.json",
    data: "",
    success: function() {
      newCount("ajax complete");
    }
  });

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