简体   繁体   中英

does using $.ajax slows down the website? what's the best way to retrieve instant data from a php file

im using alot of $.ajax calls in my website that im working on and it seems to be slow and lagging at some points. Is there any faster way to retrieve data other than using the $.ajax ?

   $.ajax({
     type: 'POST',
     url: path + 'helper/general/general.php',
     data: {pass:pass},
     success: function(data){
        if(data == 'correct'){
            $.ajax({
                type: 'POST',
                url: path + 'helper/process/ClassesProcess.php',
                data: {classID: classID}
            });
        }else{
            $('.feedback').html(wrong_password).slideDown();
        }
    }
});

Ways in which I think you could optimise this are:

  1. Use === instead of == in an if statement, this way it will check the type before the value.
  2. Instead of doing an ajax call with in an ajax call, surely your first call should do all the logic (try to avoid having logic in your front-end)
  3. Instead of returning strings or html from your ajax calls, return JSON if you can... however be wary of using json_encode/json_decode in php as they seem to be two slow functions.
  4. If the user is refreshing the page, they don't need to redownload the content for a lot of your ajax calls, if the data hasen't changed since that user's last request, return a 304 with no data instead of returning a 200 with the data. This will make the browser get the previous response from it's cache.
  5. Avoid declaring a function where there should be a callback, instead, put the name of a pre-existing function, this will stop the function being reinitialised every time you execute you ajax method.
  6. Finally, when using jQuery, try to target elements by id instead of class, jQuery finds the element a lot faster this way as ids should be unique in a webpage.

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