Javascript 替换/编码<;及>;在提交之前使用jquery/ajax

Javascript 替换/编码<;及>;在提交之前使用jquery/ajax,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我有以下代码,它是页面中注释表单的一部分 $.ajax({ type: "POST", url: "path/to/script.php", data: $(form).serialize(), success: function(data) { $('#comment_form').fadeOut(1000); var url = 'path/to/script.php'; $('#commenti').load

我有以下代码,它是页面中注释表单的一部分

 $.ajax({
    type: "POST",
    url: "path/to/script.php",
    data: $(form).serialize(),
    success: function(data) {
        $('#comment_form').fadeOut(1000);
        var url = 'path/to/script.php';
        $('#commenti').load(url + ' .comment');    
    }
});
在服务器端,像
这样的所有字符都会被剥离,但我需要它们来允许在
标记中显示代码片段

在提交之前,jquery有没有办法将
转换为
,这样评论就可以显示,而不带分隔符?

试试这个

function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}
函数htmlEncode(值){
//创建内存中的div,设置其内部文本(jQuery自动编码)
//然后把编码的内容拿回来。div在页面上永远不存在。
返回$('').text(value.html();
}
函数htmlDecode(值){
返回$('').html(value.text();
}

看看这篇文章

我还没有找到任何好的客户端解决方案,所以这里有一个php服务器端函数。 对于任何需要它的人:

function specialchars($special) {
$replace = array(
'<' => '&lt;',
'>' => '&gt;',
'&' => '&amp;'
 );
return strtr($special, $replace);
}
功能专用卡($special){
$replace=数组(
'' => '',
“&”=>”&;'
);
返回strtr($特殊,$替换);
}

根据您的需要使用函数specialchars。

使用jQuery,您可以使用此方法检索由html实体替换为<和>的字符串

var text = "<script>alert('I am XSS');<script> This is regular ol' text!";
var escapedText = $('<i>').text(text).html();
// "&lt;script&gt;alert('I am XSS');&lt;script&gt; This is regular ol' text!"

如果你的应用程序是面向WWW的,你应该确保所有的输入在输出给用户之前都经过了适当的消毒,并且值得一看

为什么不在服务器端执行呢?这似乎比剥离它们要容易得多。由于某些原因,我需要在客户端执行此操作。为我们寻找一个好的解决方案但没有成功:-(你发现哪些解决方案不好,为什么?这个问题似乎没有那么复杂,或者我遗漏了什么?到目前为止,我还没有找到任何解决方案。如果我找到了,我不会问这个问题。我需要在提交之前转换字符。上传后,任何人都可以通过disabl发送未转义的垃圾ing JS,如果这就是你所依赖的,那么它就是一个XSS。我在我们之前发现了这篇文章,但我不知道如何将它集成到ajax调用中。如果你在服务器端(应该)这样做,为什么不使用它呢?
var text = "<script>alert('I am XSS');<script> This is regular ol' text!";
var escapedText = encodeURIComponent(text);
// "%3Cscript%3Ealert('I%20am%20XSS')%3B%3Cscript%3E%20This%20is%20regular%20ol'%20text!"
// post with AJAX
echo htmlentities(rawurldecode($_POST["query"]));
// "&lt;script&gt;alert('I am XSS');&lt;script&gt; This is regular ol' text!"