I have the following JSON data that is returned from a WCF RESTful Service.
{"Cities":["LUSAKA","HARARE"],"Countries":["ZAMBIA","ZIMBABWE"]}
I am attempting to populate the following HTML Table with this data.
<table id="location" border='1'>
<tr>
<th>Countries</th>
<th>Cities</th>
</tr>
</table>
The below code works, however, it relies on the index of either the Countries or the Cities and I cannot access the data from the item variable in the anonymous function.
var trHTML = '';
$.each(data.Countries, function (i, item) {
trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';
});
$('#location').append(trHTML);
However if I attempt to access the data like this it does not work:
$.each(data.d.results,function(d, item){
$("#location tbody").append(
"<tr>"
+"<td>"+item.Countries+"</td>"
+"<td>"+item.Cities+"</td>"
+"</tr>" )
})
How do I access the data using the item variable in the loop function above?
Here is the complete working code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>WCF Client</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<table id="location" border='1'>
<tr>
<th>Countries</th>
<th>Cities</th>
</tr>
</table>
<script>
var service = 'http://localhost/DistributedDataSystem/Service.svc/';
$(document).ready(function(){
jQuery.support.cors = true;
$.ajax(
{
type: "GET",
url: service + '/GetAllCountries/',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var trHTML = '';
$.each(data.Countries, function (i, item) {
trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';
});
$('#location').append(trHTML);
},
error: function (msg) {
alert(msg.responseText);
}
});
})
</script>
</body>
</html>