I am using the following code to get a list of members and their information using ajax, jquery, php, json.
The only problem is when i use .html , it only displays the first record, it doesn’t display all of the records. Totally confused.
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function() {
var refreshId = setInterval(function(){
var friends= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url:'http://www.l.example.com/app/scrip/friends_lookup.php',
data: "",
dataType: 'json',
success: function(data){
$.each(data, function(key, val) {
var friend = val['friend'];
var phone = val['phone'];
var status = val['status'];
var email = val['email'];
var updated = val['updated'];
$('#member_friends').append("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
});
}
});
}, 1500);
});
</script>
I tried this, and it didn’t work:
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function() {
var refreshId = setInterval(function() {
var friends= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url: 'http://www.l.example.com/pp/scripts/friends_lookup.php',
data: "",
dataType: 'json',
success: function(data){
var output = [];
for (var i = 0, len = data.length; i < len; i++) {
output[output.length] = {
friend : data[i].friend,
phone : data[i].phone,
status : data[i].status,
email : data[i].email,
updated : data[i].updated
};
$('#member_friends').html("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
}
}
});
}, 1500);
});
</script>
You are over-writing the values each iteration of your
$.eachloop. Before the loop, create an array to store the data, then add to the array each iteration:The
forloop I used is quite fast, here’s a JSPerf to show the performance increase over using$.each(): http://jsperf.com/jquery-each-vs-for-loops/2Also you may have noticed that I used
output[output.length] = ...instead ofoutput.push(...). The former performs faster in old browsers (the latter performs faster in modern browsers), I tend to try to help the old browsers out since they really need the help.