Нужно знать, как вставить этот фрагмент JSON в HTML с помощью jQuery / JS - PullRequest
1 голос
/ 12 августа 2010

Мне нужно знать, как можно поместить следующий JSON в элементы с именем класса article, используя jQuery И просто немного базового JavaScript:

{"elements": [
    {
        "head": "story 1",
        "writer": "journalist 1"
    },
    {
        "head": "story 2",
        "writer": "journalist 2"
    }
]}

Попытка достичь ниже HTML. Я очень новичок в JSON и т. Д. Нужно учиться на примере ..

<div class="article">
    <h5>story 1</h5>
    <p>By: journalist 1</p>

    <h5>story 2</h5>
    <p>By: journalist 2</p>
</div>

Ответы [ 2 ]

3 голосов
/ 12 августа 2010
var data = {
    "elements": [
        {
            "head": "story 1",
            "writer": "journalist 1"
        },
        {
            "head": "story 2",
            "writer": "journalist 2"
        }
    ]};

var result = []; /* where we will store the generated HTML */

$.each(data.elements, function() {
    /* in this function, `this` refers to one of the [story] objects in the elements array */
    result.push('<h5>');
    result.push(this.head);
    result.push('</h5><p>By: ');
    result.push(this.writer);
    result.push('</p>');
});

$('<div class="article" />') /* creates the div class="article" */
    .html(result.join('')) /* merges the generated HTML from above and inserts it into the div*/
    .appendTo(document.body); /* appends the div to the page */
1 голос
/ 12 августа 2010

Это довольно просто, используя jQuery. Используйте функцию добавления:

var jsonObj = {"elements": [
    {
        "head": "story 1",
        "writer": "journalist 1"
    },
    {
        "head": "story 2",
        "writer": "journalist 2"
    }
]};

var article = $(".article");
var items = jsonObj["elements"];

var arr = [];    

for(var i = 0, len = items.length; i < len; i++)   {
   var itm = items[i];
   arr.push("<h5>" + item["head"] + "</h5><p>By: " + item["writer"] + "</p>");
}

article.append(arr.join(""));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...