2013-08-07 39 views
5

我有一些輸出json的PHP。輸出由PHP生成的JSON字符串中的HTML

<?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)); 
?> 

輸出將是這樣的:

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

而jQuery的/阿賈克斯將是:

$.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); 

和HTML輸出是:

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

所以不會像HTML一樣處理。

你能幫我嗎?

回答

5

你不需要在服務器端用htmlentities轉義html。

從您的php文件中刪除$html = htmlentities($html);

原因: ヶ輛將轉換

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

其中包括在HTML時會顯示
&lt;strong&gt;Some HTML&lt;/strong&gt; &lt;br /&gt; Some more text. 

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

我如何準備HTML的JSON呢? Stripslashes不起作用。 – Daan

+0

你是指什麼樣的準備? – Jithesh

+0

當我將HTML直接插入到JsonEncode中時,它將返回null。因爲它不是有效的JSON。有了htmlentities,JsonEncode接受了字符串作爲有效的JSON。但是,我應該使用哪個函數來將HTML準備爲有效的JSON? – Daan