javascript - 通过 settimer-function 将 textarea.value 存储到 MySQL 数据库而不丢失换行符

标签 javascript php html mysql dom

在网站EasyNote我的换行符有问题。

在正文加载时,我设置了一个计时器,每 3 秒自动上传一条笔记,如下所示:

<body onload="setInterval(uploadNote,3000);current = 1;">

uploadNote的代码是:

function uploadNote() {
    var note = current+document.getElementById(\'note\').value;  //current is the number of the note selected\' because echoed
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){}
    }
    xmlhttp.open("GET","uploadnote.php?q="+note,true);
    xmlhttp.send();
}

然后是这个 php 代码:

$note = $_GET["q"]; //contains both notenumber as first digit and note

echo($note."\n"); //for debugging reasons

$notenumber = substr($note, 0, 1);
$notecontent = substr($note, 1, strlen($note));

$notecontent = str_replace("'","''",$notecontent);
$notecontent = nl2br($notecontent);

echo($notecontent); //for debugging reasons

$request = 'UPDATE notes SET note'.$notenumber.' = "'.$notecontent.'" WHERE mail LIKE "'.$email.'"';
$result = mysql_query($request);

现在的问题是,文本区域中的换行符被完全删除,因此 php-snippet 的结果是没有换行符的文本和数据库中的文本的两倍。 但是,当我直接将它们插入数据库时​​,在文本区域中显示换行符没有问题。

非常感谢您的帮助。

编辑: 更新了 uploadNote() 函数:

function uploadNote() {
    var note = current+document.getElementById(\'note\').value;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){}
    }
    xmlhttp.open("POST","uploadnote.php",true);
    xmlhttp.send("note="+note);
}

和 PHP:

$note = $_POST["note"];

echo($note."\n");

$notenumber = substr($note, 0, 1);
$notecontent = substr($note, 1, strlen($note));

$notecontent = mysql_real_escape_string($notecontent);

echo($notecontent);

$request = 'UPDATE notes SET note'.$notenumber.' = "'.$notecontent.'" WHERE mail LIKE "'.$email.'"';
$result = mysql_query($request);

现在的问题是没有任何效果。该注释不会在 MySQL 数据库中更新。

最佳答案

您的代码存在的问题:

  1. 不要使用 GET 请求来更改服务器上的内容,而应使用 POST。
  2. 数据库查询需要转义可变部分。使用mysql_real_escape_string()写入 SQL 的值。
  3. 将数据保存到数据库时,请勿使用任何以 html 为中心的格式。您可以在将代码输出回浏览器时使用它。
  4. 在文本区域内,不允许使用任何 HTML 标记,因此使用 <br>因为换行符是错误的。

关于javascript - 通过 settimer-function 将 textarea.value 存储到 MySQL 数据库而不丢失换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19350178/

相关文章:

html - Twitter Bootstrap 的响应式表格故障

javascript - 使用 javascript 更改纸张颜色

javascript - 没有马赛克的平铺 <div> 元素

javascript - 数组在传递给函数后丢失

PHP 数组 - 分隔相同的值

javascript - HTML 多种表单,带有 2 个 JavaScript

javascript - Alfresco JavaScript,当文件上传到站点时设置自定义类型属性

php - 带有逗号和 -(连字符)的多个 explode 字符

php - 使用 Zend Framework 从 Mysql BLOB 中输入/输出数据

javascript - CSS 中带有外圆 Angular 和内圆 Angular 的多行填充文本