Reputation: 7
I am very new to programming with jQuery and I am trying to retrieve a JSON object from a json file I have locally and display the data in a table within the webpage. I have looked at several different forums for this but all of my code so far has got errors within firebug.
the closest I got was this little snippet of code to returning anything:
var vendor;
$.ajax({
async: true,
type: "POST",
url: "dataRetrieval.json",
data: "vendorId="+vendor,
success: function(json){
alert( "Data retrieved: " + json );
}
});
And when I ran that I got the following to display in the alert: Data retrieved: [object XMLDocument]
I am obviously missing something here, if someone would be able to help me out here it would be GREATLY appreciated.
Upvotes: 0
Views: 614
Reputation: 709
Verify if your JSON is valid -> http://www.jsonlint.com I'm guessing your JSON has multiple data.
HTML
<table id="table"></table>
jQuery
$.getJSON("dataRetrieval.json",function(data){
$.each(data,function(index, d){
//append data to your table as rows
$('#table').append(
'<tr>' +
'<td>' + d.row1entry1
'<\/td>' +
........
'<\/tr>'
);
});
});
Upvotes: 0
Reputation: 2679
Just add a dataType:'json'
and you should be ok:
$.ajax({
async: true,
type: "POST",
url: "dataRetrieval.json",
data: "vendorId="+vendor,
dataType: 'json',
success: function(json){
alert( "Data retrieved: " + json );
}
});
Also check out $.getJSON()
. Plus you might consider passing the data
attribute as a dictionary: data: {vendorId: vendor}
, it's a little more flexible and doesn't expose you to encoding problems when dealing with user input (eg, if a user entered "Jack & Jill" into a name field, it will escape that & sign correctly).
Upvotes: 1