简体   繁体   中英

How to parse json encoded html data to simple html in jquery

I tried some of the examples but couldn't get it to work. I have a script that produces HTML results and those results are fetched by Ajax request. But the fetched results are escaped therefore not working as normal HTML.

PHP (Just a small part)

if($count > 0){
    echo json_encode(array('heading' => '<div id="found">Here is all!</div>', 'list' => $thelist));
}
else{
    echo json_encode(array('heading' => '<div id="empty_storage"><img src="icon.png"><br>Its lonely here!</div>', 'list' => $thelist));
}

AJAX/ JQUERY

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //$("#list").html('<div id="loader"><i class="fa fa-refresh fa-fw fa-5x fa-spin" aria-hidden="true"></i><br>Waiting...</div>');
    setInterval(function(){
        $.ajax({
               type: "GET",
               url: "generate_list.php",
               dataType:"json",
               cache: false,
               success: function(result){
                     result = JSON.parse(result);
                     $("#list ul").html(result['list']);
               }
        });
    }, 1000);
});
</script>

HTML

<div id="list">
<ul>
</ul>
</div>

ERROR IN CONSOLE

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

UPDATE:

Error removed but when I try to show the data in the html tags only one shows up.

<script type="text/javascript">
$(document).ready(function(){
    //$("#list").html('<div id="loader"><i class="fa fa-refresh fa-fw fa-5x fa-spin" aria-hidden="true"></i><br>Waiting...</div>');
    setInterval(function(){
        $.ajax({
               type: "GET",
               url: "generate_list.php",
               dataType:"json",
               cache: false,
               success: function(result){
                     $("#list").html(result.heading);
                     $("#list ul").html(result.list);
               }
        });
    }, 1000);
});
</script>

WHAT $thelist CONTAINS

    $thelist .= '<li><span class="type">'.$extn.'</span><span class="link"><a href=./storage/'.$namehref.'>'.$name.'</a></span><span class="size">'.$size.'</span><span class="fa fa-trash-o fa-fw" aria-hidden="true"></span>
</li>';

Since you already added the

dataType:"json"

There will be no need to use

JSON.parse();

result in success is already formatted as JSON.

Also to use the list property of your JSON.

result.list

     $("#list ul").html(result.list);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM