我有一个小问题,在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