dqvzfp6468 2014-12-23 15:44
浏览 51
已采纳

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

I am writing simple AJAX functions to send comments to the server and save them in a mySQL database with php.

The following code seemed to work just fine for my purposes, basic but did his job, until i tried to put a hash symbol (#) in a comment. Inserting this into the text "crashes" my functions, without saving the written text in the database and returning an empty div basically.

This is the ajax call:

  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();
    ...
  }

Where createAjax simply creates the xmlhttp object for every browser as standard, validation is a function that checks for many symbols like <,>,=,(,),| with a regular expression.

this is the php part:

 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);
}

It just connects, saves the comment and returns the html code with echo, so that the javascript function can print it.

This works with any text apparently, but I can't get it to work with an hash, am I missing something? Sidenotes, I could simply add the symbol to the validation regular expr., but my point is to "print" it, not just excluding it. Thanks in advance! Sidenote 2, the javascript attaches the comment to a static element.

  • 写回答

2条回答 默认 最新

  • 普通网友 2014-12-23 15:52
    关注
    url = "comments.php?news="+n+"&text="+text;
    

    You aren't escaping any of the data you are putting into your URL.

    Some characters have special meaning, e.g. & separates query parts and # starts the fragment identifier.

    You need to run your input through encodeURIComponent() before adding it to the URL.

    url = "comments.php?news=" + encodeURIComponent(n) + "&text=" + encodeURIComponent(text);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line