我有一些与XML-RPC后端通信的JavaScript代码。
XML-RPC返回如下形式的字符串:
<img src='myimage.jpg'>
然而,当我使用JavaScript将字符串插入到HTML中时,它们会逐字呈现。我看到的不是图像,而是字符串:
<img src='myimage.jpg'>
我猜想HTML是通过XML-RPC通道转义的。
如何在JavaScript中解除字符串转义?我尝试了这个页面上的技巧,但没有成功:http://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/
诊断这个问题的其他方法是什么?
不是对你的问题的直接回应,但它不是更好为您的RPC返回一些结构(是XML或JSON或其他)与那些图像数据(在您的例子中的url)在该结构?
然后你可以在javascript中解析它,并使用javascript本身构建<img>。
你从RPC接收到的结构可能是这样的:
{"img" : ["myimage.jpg", "myimage2.jpg"]}
我认为这样更好,因为将来自外部源代码的代码注入您的页面看起来不太安全。想象一下,有人劫持了您的XML-RPC脚本,并在其中放入了一些您不想要的东西(甚至是一些javascript……)
不客气只是一个信使……全部归功于ourcodeworld.com,链接如下。
window.htmlentities = {
/**
* Converts a string to its html characters completely.
*
* @param {String} str String with unescaped HTML characters
**/
encode : function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
},
/**
* Converts an html characterSet into its original character.
*
* @param {String} str htmlSet entities
**/
decode : function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
}
};
出处:https://ourcodeworld.com/articles/read/188/encode-and-decode-html-entities-using-pure-javascript