我从图像标签中获取 src 属性,并通过 ajax 调用将其发布到我的数据库,然后用于形成 XML 文件。我真的需要转义这个图像路径并且似乎对如何做到这一点感到很困惑。尝试使用 encodeURIComponent 但运气不佳。下面是我的代码。感谢您的帮助!
$('.drag-elem').each(function () {
var xml = '<clother><id>' + $(this).children('img').attr('class') +
'</id><title>' + $(this).children('img').attr('alt') + '</title><z-index>' +
$(this).css('z-index') + '</z-index><top>' + $(this).css('top') +
'</top><left>' + $(this).css('left') + '</left><file>' +
encodeURIComponent($(this).children('img').attr('src')) +
'</file></clother>';
});
最佳答案
您必须使用 encodeURI。因为 encodeURIComponent 不适合完整路径。
尝试使用 xml 编码函数 (encodeXml) 从 amps 中清除您的 xml:
var xml_special_to_escaped_one_map = {
'&': '&',
'"': '"',
'<': '<',
'>': '>'
};
var escaped_one_to_xml_special_map = {
'&': '&',
'"': '"',
'<': '<',
'>': '>'
};
function encodeXml(string) {
return string.replace(/([\&"<>])/g, function(str, item) {
return xml_special_to_escaped_one_map[item];
});
};
function decodeXml(string) {
return string.replace(/("|<|>|&)/g,
function(str, item) {
return escaped_one_to_xml_special_map[item];
});
}
来自这里:http://dracoblue.net/dev/encodedecode-special-xml-characters-in-javascript/155/
关于javascript - 在通过 ajax 发布到数据库时试图转义 URI。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6821615/