2013-08-07 11 views
5

Ho qualche PHP che emette JSON.Output HTML in stringa JSON generata da PHP

<?php 
$html = utf8_encode($gegevens['tekst']); 
$html = htmlentities($html); 
//$html = htmlspecialchars($gegevens['tekst'], ENT_QUOTES, 'UTF-8'); 
echo json_encode(array('titel' => $gegevens['titel'], 'html' => $html)); 
?> 

L'output sarà simile:

{"titel":"Here comes the title","html":"<strong>Here is the HTML<\/strong>\n<br \/>\n<br \/>\n  And some more."} 

E il jQuery/Ajax sarà:

$.ajax({ 
          type: "GET", 
          url: "content/popup.php?id=" + id2, 
          dataType: 'json', 
          crossDomain: true, 
          success: function(json) { 
          var titel = json['titel']; 
          var html = json['html']; 


function ContentTonen() 
{ 
           // Div's legen van content 
$('.popup_home_head_inside').empty(); 
$('.popup_home_content_inside').empty(); 

$('.popup_home_head_inside').html(titel); 
var html2 = html.replace(/\"/g, ""); 
//$('.popup_home_content_inside').html(html2); 
$('.popup_home_content_inside').html(html2); 

E l'output HTML è:

<strong>Some HTML</strong> <br /> Some more text. 

Così non elaborerà come HTML.

Potete aiutarmi?

risposta

5

Non è necessario evitare l'html con htmlentities sul lato server.

Rimuovi il $html = htmlentities($html); dal tuo file php.

Motivo: htmlentities convertiranno

<strong>Some HTML</strong> <br /> Some more text. 

a

&lt;strong&gt;Some HTML&lt;/strong&gt; &lt;br /&gt; Some more text. 

che, se inclusi in HTML visualizzerà:

<strong>Some HTML</strong> <br /> Some more text. 
+1

Come mi preparo il codice HTML per JSON, allora? Stripslashes non funziona. – Daan

+0

Che tipo di preparazione intendi? – Jithesh

+0

Quando inserisco l'HTML direttamente in JsonEncode restituisce null. Perché non è valido JSON. Con htmlentities JsonEncode ha accettato la stringa come JSON valido. Ma quale funzione dovrei usare per preparare l'HTML come JSON valido? – Daan