使用井号标记保存文本(Javascript - PHP - MySQL)

时间:2014-12-23 15:44:05

标签: javascript php mysql ajax

我正在编写简单的AJAX函数来向服务器发送注释,并使用php将它们保存在mySQL数据库中。

以下代码似乎对我的目的起作用,基本但是完成了他的工作,直到我试图在注释中添加哈希符号(#)。 将其插入文本"崩溃"我的函数,没有在数据库中保存书面文本并基本上返回一个空div。

这是ajax电话:

  function sendComment(n){
    var xmlhttp = createAjax();

    var text = document.getElementById("f"+n).value;
    if (!validation(text))
       return false;

    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState==4 && xmlhttp.status==200){
        appendComment(n, xmlhttp.responseText);
       }
    }
    ...
    url = "comments.php?news="+n+"&text="+text;
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    ...
  }

createAjax只是为每个浏览器创建xmlhttp对象作为标准,验证是一个检查许多符号的函数,如<,>,=,(,),|用正则表达式。

这是php部分:

 function insertComment($text, $news){
    $conn = dbConnect();

    $user = $_SESSION["user"];
    $text = nl2br(htmlentities($text));
    $date = date("Y-m-d H:i:s");
    $sql = "INSERT INTO comments(user, news, date, text) VALUES ('".$user."','".$news."','".$date."', '".$text."')";
    mysql_query($sql) or die ("Errore in inserimento: ".sql_error());
    echo writeSingleComment($user, $date, $text);
    mysql_close(conn);
}

它只是连接,保存注释并使用echo返回html代码,以便javascript函数可以打印它。

这显然适用于任何文本,但是我无法使用哈希,我错过了什么? 侧面注释,我可以简单地将符号添加到验证常规expr中,但我的观点是" print"它,而不仅仅是排除它。提前致谢! 侧面2,javascript将注释附加到静态元素。

2 个答案:

答案 0 :(得分:2)

url = "comments.php?news="+n+"&text="+text;

您无法转发您放入网址的任何数据。

某些字符具有特殊含义,例如&分隔查询部分,#启动片段标识符。

在将其添加到网址之前,您需要通过encodeURIComponent()运行输入。

url = "comments.php?news=" + encodeURIComponent(n) + "&text=" + encodeURIComponent(text);

答案 1 :(得分:-2)

许多字符(例如#)不是SQL安全的并且需要转义 至少你需要使用

var toSend = escape(mystring);

这不会保护您免受攻击,但会让您无所事事。