javascript - 如何使用 jQuery Ajax 将数据从 JSON 添加到 HTML?

标签 javascript jquery ajax

我想将 JSON 对象中的数据添加到 HTML 标记中。我使用 jQuery 和 AJAX 来读取数据。我想要实现的是,将为 JSON 文件中的每个对象添加一个代表项目的新 HTML 标记。

我使用以下代码从每个对象添加 text 键。

$.ajax({
    url: 'api/videoData.js',
    dataType: 'json',
    success: function(data) {
        console.log(data); //uncomment this for debug

        for (var i = 0; i < data.content.length; i++) {
            if (data.content[i].type == 'normal') {
                console.log(data.content[i].text);
                $('.article.text').find('p').html(data.content[i].text);
            }
        };
    },
    error: function() { 
        console.log('Houston, we have a problem!');
    }
});

HTML 标记:

<div class="article text">
    <span class="format text alignRight"></span>

    <h4>Subtitle</h4>
    <h3>Title</h3>
    <p>
        Paragraph text
    </p>
</div><!-- End div.article text -->

JSON 文件:

{
    "title":    "London",
    "category": "The Ultimate",
    "image":    "images/content/londen.jpg",
    "website":  "http://www.london.nl/",
    "youtube":  "https://www.youtube.com/watch?v=Sq9rjbouBlY&t=23",
    "maps":     "https://www.google.nl/maps/place/Londen,+Verenigd+Koninkrijk/@51.5114089,-0.1271477,13.79z/data=!4m2!3m1!1s0x47d8a00baf21de75:0x52963a5addd52a99",
    "content":  [
        {
            "type" :        "normal",
            "timeTrigger":  24,
            "title":        "London Eye",
            "subtitle":     "Algemene",
            "picture" :     "images/content/london.jpg",
            "text":         "This is the London Eye",
            "readmore":     "http://wikitravel.org/en/London"
        },{
            "type":         "normal",
            "timeTrigger":  24,
            "title":        "Sherlock Holmes",
            "subtitle":     "Detective",
            "picture" :     "images/content/sherlock_holmes.jpg",
            "text":         "Sherlock Holmes is een fictieve detective  <br> uit de verhalen van de laat-19de-eeuwse",
            "readmore":     "http://nl.wikipedia.org/wiki/Sherlock_Holmes"
        },{
            "type":         "normal",
            "timeTrigger":  39,
            "title":        "Fish \"n Chips",
            "subtitle":     "Eten",
            "picture" :     "images/content/sherlock_holmes.jpg",
            "text":         "Fish and chips is een typisch Britse afhaalmaaltijd .",
            "readmore":     "http://youngandfoodish.com/london/top-10-fish-and-chips-in-london/"
        }
    ]
}

它将 console.log 我所有对象的所有文本,但它不会出现在我的 HTML 中。

最佳答案

您应该使用 append 而不是 html 因为:

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content.

来自 jquery API:API .html()

您还可以使用 jquery each 代替 for 循环: API $.each()

使用如下标记来附加您的文章:

<div id="articles"></div>

...你的ajax:

$.ajax({
        url: 'api/videoData.js',
        dataType: 'json',
        success: function(data) {
            console.log(data); //uncomment this for debug
            Triptube.dataController.timelineEvents(data);

            //the element where the articles should be appended
            var el = $('#articles');

            //empty this element first
            el.empty();

            //you can use jquery each to append all new articles
            $.each(data.content, function(index, value) {
                if (value.type == 'normal') {
                    console.log(value.text);

                    //append every node instead of replacing it with your markup
                    el.append(
                       '<div class="article text">' +
                          '<span class="format text alignRight"></span>' +
                          '<h4>' + value.subtitle + '</h4>' + 
                          '<h3>' + value.title + '</h3>' +
                          '<p>' + value.text + '</p>' +
                       '</div>'
                    );

                }
            });
        },
        error: function() { // Moet deze ook een parameter hebben?
            console.log('Houston, we have a problem!');
        }
});

API:

API .empty

API .append()

关于javascript - 如何使用 jQuery Ajax 将数据从 JSON 添加到 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33119917/

相关文章:

javascript - 这个跨域ajax请求是如何工作的?

javascript - 为什么我的 httpresponse 是空的?

javascript - 如何使用 Javascript 和 Anchor 标签调整用户的 View

javascript - 为子实例创建同名属性,而父属性的可写为假

javascript - 使用 jQuery 在 ajax 调用中仅发送数组中对象的少数属性

javascript - 如何正确使用多个初始化函数?

javascript - lightgallery 不适用于动态生成的元素

javascript - Angular : get select label without modifying ng-model

javascript - 用JS下载文件按钮

javascript - 模板代码创建指数数量的元素