Reputation: 993
I'm trying to use a Json database to read a large amount of data into a html document using jQuery. The code I'm using now is as follows:
$(document).ready(function($) {
$.getJSON("http://mtgjson.com/json/BNG.json",
function(data){
console.log(data);
$.each(data.cards, function(i,card){
content += '<p>' + card.name + '</p>';
content += '<p>' + card.rarity + '</p>';
content += '<p>' + card.manaCost + '</p>';
content += '<p>' + card.type + '</p>';
content += '<br/>';
$(content).appendTo("#content");
});
});
});
The code seems to work because it returns the data I requested (name, rarity, manacost and type) it doesn't show it in the div named #content. It shows the data only in an error message in the DOM.
Uncaught Error: Syntax error, unrecognized expression: [object HTMLDivElement]<p>Acolyte's Reward</p><p>Uncommon</p><p>{1}{W}</p><p>Instant</p><br/>
I think it has something to do with appending the $(content) to ("#content"), but I'm really new to Json so I can't for the life of me figure it out.
And yes, I have a div named #content in my html before someone asks. Thanks in advance.
Edit: Console log data as requested:
Object {name: "Born of the Gods", code: "BNG", releaseDate: "2014-02-07", border: "black", type: "expansion"…}
block: "Theros"
booster: Array[16]
border: "black"
cards: Array[165]
code: "BNG"
name: "Born of the Gods"
releaseDate: "2014-02-07"
type: "expansion"
__proto__: Object
Upvotes: 0
Views: 87
Reputation: 388316
You need to create a local variable, looks like content
is referring to some element
$(document).ready(function ($) {
$.getJSON("http://mtgjson.com/json/BNG.json", function (data) {
console.log(data);
$.each(data.cards, function (i, card) {
var content = '<p>' + card.name + '</p>';
content += '<p>' + card.rarity + '</p>';
content += '<p>' + card.manaCost + '</p>';
content += '<p>' + card.type + '</p>';
content += '<br/>';
$(content).appendTo("#content");
});
});
});
Demo: Fiddle
In your case you have an object with id content
, so the global variable content
refers to that dom element. This causes the string concatenation to result in wrong value
Upvotes: 3