PDA

View Full Version : Show all Array? .each()?



jarv
01-28-2011, 12:02 AM
hi,

I am sooo close to getting my project done,

I can now output a town name, using Jquery to output mySQL as JSON

the only problem I have now... In my code I have [16] which = 'Andover'

Is there a way to output my whole array? can I use .each()? if so, where?

thanks

here is my code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {

$.getJSON('json.php', function(data){

$("#content").html(data[16].Town);

});

});
</script>
</head>
<body>

<div id="content"></div>
</body>
</html>


http://www.mypubspace.com/dashtest/newjson.html

devnull69
01-28-2011, 12:15 AM
.each() will iterate through jQuery objects ... to iterate simple arrays, you can use something like this:


$.getJSON('json.php', function(data){
var myhtml = '<ul>';
for(i=0; i<data.length; i++) {
myhtml += '<li>' + data[i].Town + '</li>';
}
myhtml += '</ul>';
$("#content").html(myhtml);
});

This will give you a complete unordered list with the towns as list items. But you can compose the string in any way you want.

oesxyl
01-28-2011, 12:36 AM
.each() will iterate through jQuery objects ... to iterate simple arrays, you can use something like this:


$.getJSON('json.php', function(data){
var myhtml = '<ul>';
for(i=0; i<data.length; i++) {
myhtml += '<li>' + data[i].Town + '</li>';
}
myhtml += '</ul>';
$("#content").html(myhtml);
});

This will give you a complete unordered list with the towns as list items. But you can compose the string in any way you want.
or use $.each which works with both objects and arrays, :)

http://api.jquery.com/jQuery.each/

best regards

jarv
01-28-2011, 12:43 AM
thanks, how would I implement $.each into my code?

thanks

oesxyl
01-28-2011, 12:59 AM
thanks, how would I implement $.each into my code?

thanks
using devnull69 is something like this but is not tested:


$.getJSON('json.php', function(data){
var myhtml = '<ul>';
$.each(data, function(ind, val){
myhtml += '<li>' + val.Town + '</li>';
}
myhtml += '</ul>';
$("#content").html(myhtml);
});


best regards