最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create HTML from JSON object - Stack Overflow

programmeradmin2浏览0评论

Here I have sme .ajax function that work well:

 $( document ).ready(function() {
$('a#kom').click(function (e) {
    var tabela = 'parcele';
      $.ajax({
            url: "getComments.php",
            type: "POST",
            async: true, 
            data: { ajdi:ajdi,tabela:tabela}, //your form data to post goes here as a json object
            dataType: "html",

            success: function(data) {
            console.log(data);  
            },
            error:function(data) {
            console.log(data); 
            }
        });

        });
        }); 

and this function produce this JSON:

[{"datum":"2014-05-22","komentar":"Testiranje za komentare da vidimo kako moze da sluzi, dali radidobro, bla bla bla bla bla bla bla bla bla bla bla bla ... ..."}] 

Iknow its a basic question but I cant find any good resource... How I can into .ajax function when function is success to create this html:

'<div class="notes">
        <h4>Tekst zaglavlje</h4>
        <h5>'+datum+'</h5>
        <p>'+komentar+'</p>
    </div>'

for every object I get from JSON... so like that:

            success: function(data) {
            // CREATE A HTML FROM JSON DATA FOR EACH JSON OBJECT. HOW?
            console.log(data);  
            },

UPDATE WITH PHP

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { 

    try {


     $result = $db->prepare("SELECT * FROM komentari WHERE id_utabeli=:ajdi AND tabela=:tabela");
     $result->execute(array(':ajdi' => $_POST['ajdi'], ':tabela' => $_POST['tabela']));
    $result = $result->fetchAll(); 

     $temp = array();
foreach($result as $r) {

          $temp[] = array('datum' => (string) $r['datum'], 'komentar' => (string) $r['komentar']); 

        }
    $table = $temp;
    $jsonTable = json_encode($table);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    echo $jsonTable;
}
    else { 
echo 'ERROR 404';
  }  

Here I have sme .ajax function that work well:

 $( document ).ready(function() {
$('a#kom').click(function (e) {
    var tabela = 'parcele';
      $.ajax({
            url: "getComments.php",
            type: "POST",
            async: true, 
            data: { ajdi:ajdi,tabela:tabela}, //your form data to post goes here as a json object
            dataType: "html",

            success: function(data) {
            console.log(data);  
            },
            error:function(data) {
            console.log(data); 
            }
        });

        });
        }); 

and this function produce this JSON:

[{"datum":"2014-05-22","komentar":"Testiranje za komentare da vidimo kako moze da sluzi, dali radidobro, bla bla bla bla bla bla bla bla bla bla bla bla ... ..."}] 

Iknow its a basic question but I cant find any good resource... How I can into .ajax function when function is success to create this html:

'<div class="notes">
        <h4>Tekst zaglavlje</h4>
        <h5>'+datum+'</h5>
        <p>'+komentar+'</p>
    </div>'

for every object I get from JSON... so like that:

            success: function(data) {
            // CREATE A HTML FROM JSON DATA FOR EACH JSON OBJECT. HOW?
            console.log(data);  
            },

UPDATE WITH PHP

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { 

    try {


     $result = $db->prepare("SELECT * FROM komentari WHERE id_utabeli=:ajdi AND tabela=:tabela");
     $result->execute(array(':ajdi' => $_POST['ajdi'], ':tabela' => $_POST['tabela']));
    $result = $result->fetchAll(); 

     $temp = array();
foreach($result as $r) {

          $temp[] = array('datum' => (string) $r['datum'], 'komentar' => (string) $r['komentar']); 

        }
    $table = $temp;
    $jsonTable = json_encode($table);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    echo $jsonTable;
}
    else { 
echo 'ERROR 404';
  }  
Share Improve this question edited May 23, 2014 at 9:14 gmaestro asked May 23, 2014 at 8:46 gmaestrogmaestro 3397 silver badges26 bronze badges 1
  • 2 Read this developer.mozilla/en-US/docs/Web/API/document.createElement – Klemen Tusar Commented May 23, 2014 at 8:47
Add a ment  | 

4 Answers 4

Reset to default 3

You have a wrong dataType that should be:

dataType: "json", 

because response is json not a html.

In your success function do this:

success: function(data) {
    var htm = '';  
    $.each(data, function(i, resp){
        htm +='<div class="notes">' + 
                 '<h4>Tekst zaglavlje</h4>' +
                 '<h5>'+resp.datum+'</h5>' +
                 '<p>'+resp.komentar+'</p>' +
             '</div>';
    }); 
    $('yourContainer').html(htm);
},

As your response seems to be an array [{},{}....] or multiple javascript objects so to produce such html markup you have to loop in that array with $.each() method and declare one blank var htm=''; before $.each() iteration and concatenate the resulting html out of your json, then place at the position of your container which can hold the produced html.


Find a Demo @ Fiddle

Since you're using jquery, you can do this like follows:

$( document ).ready(function() {
    $('a#kom').click(function (e) {
        var tabela = 'parcele';
        $.ajax({
            url: "getComments.php",
            type: "POST",
            async: true, 
            data: { ajdi: ajdi, tabela: tabela },
            dataType: 'json',
            success: function(data) {
                console.log(data);  

                $.each(data, function(i, item) {
                    // create html
                    var elem = '<div class="notes">
                                    <h4>Tekst zaglavlje</h4>
                                    <h5>' + item.datum + '</h5>
                                    <p>' + item.komentar + '</p>
                                </div>'

                    $('body').append(elem); // append the item
                });
            },
            error: function(data) {
                console.log(data); 
            }
        });
    });
});

Your success function should look like this:

success: function(data) {
    notes_div = $("<div/>");
    hfour = $("<h4/>").text("Tekst zaglavlje");
    hfive = $("<h5/>").text(data.datum);
    para = $("<p/>").text(data.komentar);
    notes_div.append(hfour).append(hfive).append(para);
    $('#komenatri').append();
},

Other answers provided that just build your HTML as a string are not safe. They open you up to XSS (google it ;) ) but we fix that by making elements as JQuery objects and setting their .text() which makes the resultant content HTML safe.

You should also run your data through htmlspecialchars() in PHP before outputing it.

change:

$temp[] = array('datum' => (string) $r['datum'], 'komentar' => (string) $r['komentar']);

To

$temp[] = array('datum' => htmlspecialchars( (string) $r['datum'] ), 'komentar' => htmlspecialchars( (string) $r['komentar']) );

This will prevent users from injecting their own HTML into your pages with their ments.

success: function(data) {
    for(var i = 0, ceiling = data.length; i < ceiling; i++) {
        document.getElementById("komenatri").innerHTML += 
            "<div class=\"notes\"><h4>Tekst zaglavje</hr><h5>" + 
            data[i].datum + 
            "</h5><p>" + 
            data[i].komentar + 
            "</p></div>";
    }
}
发布评论

评论列表(0)

  1. 暂无评论