2014-01-23 131 views
0

這是js代碼JavaScript變量包含純文本包括HTML標籤

function startChatSession(){ 
$.ajax({ 
    url: "chat.php?action=startchatsession", 
    cache: false, 
    dataType: "json", 
    success: function(data) { 

    username = data.username; 

    $.each(data.items, function(i,item){ 
     if (item) { // fix strange ie bug 

      chatboxtitle = item.f; 

      if ($("#chatbox_"+chatboxtitle).length <= 0) { 
       createChatBox(chatboxtitle,1); 
      } 

      if (item.s == 1) { 
       item.f = username; 
      } 

      if (item.s == 2) { 
       $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>'); 
      } else { 
       $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>'); 
      } 
     } 
    }); 

這裏+ item.m +持有明文

,如果它包含HTML標記,然後返回HTML標籤也

例如+ item.m +包含

<b>Hello</b> 

我想輸出是

你好

但我得到相同的輸出

<b>Hello</b> 

這個代碼在IM聊天來實現,我需要的html代碼在聊天窗口中執行。 。 。所以請幫我建議得到執行HTML這裏

謝謝

+0

它看起來像'item.m'可能使用HTML實體而不是文字'<' and '>'字符。 – crush

+0

'item.m'中的HTML標籤必須使用htmlentities或類似的東西進行編碼。因此,它們不會被瀏覽器解釋爲HTML標籤。 –

+1

檢查輸出是否爲html編碼,例如它實際上是'<b>你好...'。 –

回答

1

看來你有&lt;b&gt,而不是一個真正的<br>,解決它做到這一點:

var itemText = item.m 
    .replace(/&lt;b&gt;/g, '<b>') 
    .replace(/&lt;\/b&gt;/g, '</b>'); 

然後在代碼中使用itemText代替item.m,像這樣:

 var itemText = item.m 
      .replace(/&lt;b&gt;/g, '<b>') 
      .replace(/&lt;\/b&gt;/g, '</b>'); 
     if (item.s == 2) { 
      $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+itemText+'</span></div>'); 
     } else { 
      $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+itemText+'</span></div>'); 
     } 

,如果你想這樣做的一些其他標籤是這樣的:

<a href="chat.php">Hello</a> 

你可以做到這一點,如:

var itemText = item.m 
    .replace(/&lt;\/a&gt;/g, '</a>') 
    .replace(/&lt;a/g, '<a') 
    .replace(/&gt;/g, '>'); 
+0

u能請告訴這將是替換代碼Hello,感謝 – ManojGeek

+0

@Raj:我更新了我的答案''Hello和 –

+0

什麼雙引號? – ManojGeek

1

在PHP端,不使用ヶ輛()給你返回內容進行編碼。當您這樣做時,服務器分別返回字符<>的HTML代碼,分別爲&lt;&gt;

+0

在PHP方面我有$ chat ['message'] = sanitize($ chat ['message']); ,這是什麼意思 – ManojGeek

+0

sanitize是你的代碼中定義的函數,檢查它做了什麼。我敢打賭,你什麼都叫它htmlentities() –

+0

對不起,我發現功能淨化($文本){ \t $ text = htmlspecialchars($ text,ENT_QUOTES); $ text = str_replace(「\ n \ r」,「\ n」,$ text); \t $ text = str_replace(「\ r \ n」,「\ n」,$ text); \t $ text = str_replace(「\ n」,「
」,$ text); }這個函數 – ManojGeek

1

看起來您正在接收來自服務器的編碼文本。嘗試在連接字符串之前在字符串上應用unescape()。

1

解碼的HTML實體,使用的.html jQuery的功能,譯碼實體

item.m = $('<div>').html(item.m).text(); 

,但我建議你刪除服務器端的實體,我看你正在開發一個聊天,所以你最好刪除任何HTML標籤的安全問題不知道你如何處理消息,但用戶有時可以做跨站點腳本。