我有一個小問題,在jQuery的jQuery的jQuery數據動態生成,但我的聊天代碼不會工作,如果用戶命中\ &或&或\任何建議 PHP代碼動態創建json,但如何防止&符號(&)和反斜槓()
<?
header('Content-type: application/json');
?>
{ "items": [ <?php echo $items;?> ]}
<?
這不會工作
{
"s": "0",
"n":"Praveen Jain",
"f": "100025",
"m": "\&"
},
這項工作:
{
"s": "0",
"n":"Praveen Jain",
"f": "100025",
"m": "\\&"
},
有任何幫助......我知道JSON禁止 '\' 和 '&' 這兩個字符
處理JSONjs代碼
function startChatSession(){
$.ajax({
url: "hsdrt/chkat.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
chatboxid = item.n;
chatboxtitle = item.f;
if ($("#chatbox_"+chatboxtitle).length <= 0)
{createChatBox(chatboxtitle,chatboxid,1);}
if (item.s == 1)
{item.n = 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.n+' </span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
}
}
});
for (i=0;i<chatBoxes.length;i++) {
chatboxtitle = chatBoxes[i];
$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
setTimeout('$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);', 100); // yet another strange ie bug
}
setTimeout('chatHeartbeat();',chatHeartbeatTime);
}
});
}
如果你知道這兩個是隻有其中,創建問題,然後創建可以JSON數據之前字符在php – Sumant 2012-03-14 08:33:08
中使用'str_replace'函數改變它們,我試過了,但是沒有運行str_replace('\&','\\&',$ items); – viveksaxena 2012-03-14 09:22:57
試試這段代碼'function convertSpecialChars($ string){ $ string = str_replace(「&」,「&」,$ string); $ string = str_replace('/','//;',$ string); return $ string; }'並且以相同的方式添加你想要修改的字符串 – Sumant 2012-03-14 10:20:45