jQuery加载JSON [英] jQuery Load JSON

查看:89
本文介绍了jQuery加载JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小难题,希望应该很容易解决.

I've got a small dilemma, that should hopefully be easy to resolve.

我正在使用jQuery/JSON/PHP加载一些数据-本质上,正在加载的数据是几个<li>元素.

I am loading some data using jQuery/JSON/PHP-- essentially, the data being loaded are several <li> elements.

以下代码可以正常工作:

The following code works correctly:

function load_list() {
$.getJSON('json/load.php', function(data) {
            $.each(data, function(k, v){                                 
            $("#my_div").append('
                                         <li> \
                                          <div> \
                                           <input type="checkbox"> \
                                          </div> \
                                          <div>'+v.due_date+'</div> \
                                          <h3> \
                                           <span>'+v.title+'</span> \
                                           </h3> \
                                          </li> \
                                                  ');
                                        });
});
}

但是,假设我要更新"#my_div"并稍后(例如,每20秒一次)再次调用该函数.如果我重新调用上面的函数,它实际上会再次追加项目,从而复制结果.

However, let's say I want to update "#my_div" and call the function again later on, say, every 20 seconds. If I re-call the function above, it actually appends the items again, thus duplicating the results.

我的问题是(原谅我不知道):如何重写上面的函数以加载所有事件并刷新它,并将"#my_div"的HTML设置为全新的而不是不重复?

My question is (forgive me for not knowing): How can I rewrite the function above to load all events and refresh it and set the HTML of the "#my_div" to be brand new and not to not duplicate?

非常感谢.

推荐答案

在包含.each()调用的匿名函数的开始处调用$("#my_div").empty().

Call $("#my_div").empty() at the beginning of the anonymous function containing the .each() call.

这篇关于jQuery加载JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆