简体   繁体   中英

jQuery append, wait till rendered with no timeout

I've an AJAX that appends HTML to page with jQuery append method. The HTML is somewhat big and I want to get the colors of the cells, those colors are set by CSS in the same HTML document.

My problem is, that if I loop the cells right after the append method, all cells have no color, I've to wait a few seconds for it to work. Right now, I'm doing a timeout to start looping through the cells, but I don't want to do that. I want to know 1) why the page is not rendered with append, why append returns before the html is fully rendered and 2) what alternatives do I have.

I'm thinking on puting an interval to check for some specific value of a cell, at the end of the HTML, but I'm not very happy with that approach.

Thanks!

Don't use intervals on AJAX responses. They work if you set the timeout to long enough, but you have to set the timeout to the maximum you'd imagine the request to take, which still has a chance of failing even after 5 seconds. Also, if the request takes a millisecond, nothing will happen for another 4.99 seconds (if 5 seconds is your timeout).

AJAX functions take several parameters. Some of those are strings (like "Content-Type: 'application/json'"). Some are objects (like data:{requestId: 999} ). You can also provide other functions as parameters. $.ajax() takes such arguments (called 'callbacks') and executes the depending on what comes back from the request. You can provide an error: callback that will only execute when there is an error (like 404 or 500). There is a success: callback that will execute immediately after the content is successfully fetched, whether that be 1 millisecond or 5 seconds. That's probably what you want.

Wherever you are passing in arguments to your $.ajax() function, give it something like the following:

//...other arguments

success: function(response){
    $('#myTable').html(response);
});

//..other arguments

That function will execute exactly if/when there is a successful response from the server. I should have mentioned that this callback can take arguments of its own. Among others, the actual content from the request is one of them (in the above example that's the first argument, response ). Whether you have XML or JSON or even HTML, that's what will be in your response for the function to act on accordingly.

You may already be using callbacks, but since there's no code and I saw 'timeout' paired with the word 'AJAX', I'm guessing that this is your answer.

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