jquery ajax load method: only one request for multiple elements?

廉价感情. 提交于 2019-12-11 06:19:33

问题


Hey, I have 10 "ul.rating" elements on my page. I want to refresh those elements every minute.

var reload = 60000;
var currentpage = window.location;
setInterval(function() {

    $('ul.ratings').load(currentpage + " .ul.ratings >*", function() {
        //callback
    });

}, reload);

Now I have the following two problems.

  1. I need to find away to reload each element new. Right now I'm probably reloading the SAME ul.ratings element for all ul.ratings elements on my page. So there must be some way to use index() or some other jquery method to reload the first ul.ratings element with the first ul.ratings element and reload the fifth ul.ratings element with the fifth ul.ratings elment.

  2. The whole thing is probably a rather bad way to do this, but I guess in my case there is no better way. Is it possible to do the load-method just ONCE and grab each ul.ratings element and replace the correct one? Right now I'm doing the load-calls if there are 10 ul.ratings elements on my page.

Thank you for your help!


回答1:


Do you have control over the URL that you call? Can you make it return only the data that you want? In that case, let it return JSON or XML and reload your ul's with that information.

Otherwise, you could use the $.get function, load the HTML in jquery and find the ul's yourself:

var ulorigs = $('ul.ratings');
$.get('url', function (data) { 
  var content = $(data);
  $('ul.ratings', content).each(function(ind,elem) {
    $(ulorigs.get(0)).html($(elem).html());
  });
});

I did not run this code myself.




回答2:


I don't have a page to try this on myself but presumably:

var reload = 60000;
var currentpage = window.location;

setInterval(function() {

    $('ul.ratings').each(function(i, el) {
        $(this).load(currentpage + " ul.ratings:eq(" + i + ") > li", function() {
            //callback
        });

    });
}, reload);

I think your primary problem is not accounting for targeting WHICH ul's content you're replacing.

This is probably a pretty crummy idea because ultimately you're talking about firing this ten times and asynchronously loading the page 10 times.

I suppose that means there's always:

$("body").load(currentpage + " body > *")

;)



来源:https://stackoverflow.com/questions/5046098/jquery-ajax-load-method-only-one-request-for-multiple-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!