jQuery Load JSON
I've got a small dilemma, that should hopefully be easy to resolve.
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开发者_如何学Python>'+v.due_date+'</div> \
<h3> \
<span>'+v.title+'</span> \
</h3> \
</li> \
');
});
});
}
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 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?
Thanks very much.
Call $("#my_div").empty()
at the beginning of the anonymous function containing the .each()
call.
You can call the html
function to set an element's HTML content, like this:
$("#my_div").html('
<li> \
<div> \
<input type="checkbox"> \
</div> \
<div>'+v.due_date+'</div> \
<h3> \
<span>'+v.title+'</span> \
</h3> \
</li> \
');
Use html
instead append
Use the html('<li>...')
tag -- it replaces content rather than appends it.
Dodinas, you'd want to use the following:
$("#my_div").html('<li>...</li>');
using the html() method inserts the html.
精彩评论