jQuery animation only if ajax information is not the same
I have a timer every 20 seconds using setInterval, it uses jQuery's ajax function load() to set the toparticles div with the information from another URL on site. Once that load is successful, it performs a jQuery highlight effect on开发者_如何学C the first article in the toparticles div. All articles on both places are held in their own seperate table, so I use #toparticles table:first.
I only want to perform the loading into the toparticles div, AND the animation if the first article is not the same.
So the concept is as follows: Every 20 seconds: Check this url, if the first table isn't equal to the first table of the page you're on, reload the entire div with that url's information, then perform highlight animation.
My current code:
setInterval(function() {
$("#toparticles").load("http://myarticles/feed/of/top/articles", function()
{
$("#toparticles table:first").effect("highlight", {color:"#f2f37f"}, 1000);});
}, 20000);
Thanks if you can provide any help.
A naive approach (best would be to have some sort of id) is
setInterval(function() {
var first_html = $("#toparticles table:first").text();
$("#toparticles").load("http://myarticles/feed/of/top/articles", function()
{
if ( first_html == $("#toparticles table:first").text() )
{
$("#toparticles table:first").effect("highlight", {color:"#f2f37f"}, 1000);
}
});
}, 20000);
It stores the text of the first table in a variable before the ajax call, and then compares it to the new first table. (i only check for text, you could change that to .html()
to check for the whole html structure if you want that level of detail)
You could probably change your request to use jQuery.ajax(). It has an "ifModified" option. From the docs:
ifModifiedBoolean Default: false
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.
jQuery.ajax() documentation
Also, I haven't checked myself but it seems as though they have an example that uses the .load()
function's call back:
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
精彩评论