简体   繁体   中英

how to output correct html with json using ajax

Hi I would like to output the code in [json['information'] as actual converted html code.

At the moment it seems to be just outputting the entire string as pure text (unformatted html, so you can see all the tags etc) Im still learning about json so am unsure what is supposed to be done with the content recieved to make it proper html.

Thanks in advance

$('.engineering-services').live('click', function() {     
$.ajax({
    url: 'index.php?route=information/information/homepage_info',
    type: 'post',
    data: {info_for : 'engineering'},
    dataType: 'json',
    success:    function(json){

    $('#engineering-content').html(json['information']);
    },
    error: function(json) {
    alert('fail');
    }
    });
   });

EDIT, heres the PHP ...

    public function homepage_info() {
    $this->load->model('catalog/information');
    $json = array();
    if (isset($this->request->post['info_for'])) {
        if ($this->request->post['info_for'] == 'engineering') {    
            $information_info = $this->model_catalog_information->getInformation(10);
            $json['information'] = $information_info['description'];                
            }
            $this->response->setOutput(json_encode($json));
            }

            }

Your HTML strings seem to be encoding special characters as HTML entities, like < to &lt; , etc. From the PHP you've shown, it's probably encoded in the database (maybe you're encoding before saving).

You should be able to fix it with html_entity_decode :

$json['information'] = html_entity_decode($information_info['description']);
// or, a few lines later:
// $this->response->setOutput(html_entity_decode(json_encode($json)));

Looks like you are using Open cart for you php controller. In order to send back aa response with the proper json headers the Open Cart way is as follows:

$this->load->library('json');
$this->response->setOutput(Json::encode($json));

Hope that helps.

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