如何将用户输入换行保存到数据库。 (jQuery的/ PHP / MySQL的)

时间:2011-12-30 00:46:47

标签: php jquery mysql

问题是: 如何将用户输入换行保存到数据库。 (jQuery的/ PHP / MySQL的)

我有一个可由用户编辑的段落。

<p contenteditable="true" id="forbiddenField">Text</p>

当我从db检索数据时:

<p contenteditable="true" id="forbiddenField"><?php echo nl2br($forbidden); ?></p>

这很有效。

onblur(.blur)将激活一个jQuery脚本,该脚本将新编辑的数据发送到数据库。

$("#forbiddenField").blur(function(){
        var whatIsNowForbidden = encodeURI($("#forbiddenField").text());

        $.ajax({
            type: "POST",  
            url: "updateForbidden.php",  
            data: "forbiddenStuff="+ whatIsNowForbidden,
            success: function(){
            }  
        });
});

问题: 如果用户使用换行符插入新数据,则不会将换行符添加到数据库中的数据中,只会添加内容。

我尝试过这个: var whatIsNowForbidden = encodeURI($(“#forbiddenField”)。text());

我看了看这些地方的答案: New Line in Textarea to be converted to <br/> http://www.w3schools.com/tags/ref_urlencode.asp Is replacing a line break UTF-8 safe? how to escape input but save unescaped into the database How to recognize every linebreak?

我无法让它发挥作用。 所有输入和提示都非常感谢!

1 个答案:

答案 0 :(得分:0)

尝试从您的javascript中删除encodeURI()功能,如下所示:

var whatIsNowForbidden = $("#forbiddenField").text();

我做了一个小小的测试,javascript的encodeURI()函数似乎没有将段落中的新行转换为%0A,就像我们期望的那样。

通过删除函数encodeURI() PHP应该能够将文本(包括新行)保存到数据库中。然后,PHP的nl2br()应该将新行转换为<br />标记,没有任何问题。

这里有小提琴:http://jsfiddle.net/LN7QC/

最终答案:使用<textarea>

jQuery:

$("#forbiddenField").blur(function(){
        var whatIsNowForbidden = $("#forbiddenField").val();

        $.ajax({
            type: "POST",  
            url: "updateForbidden.php",  
            data: "forbiddenStuff="+ whatIsNowForbidden,
            success: function(){
            }  
        });
});

添加到数据库:

<?php
    include('connect.php');

            if($_POST['forbiddenStuff']){
                $forbiddenInput = $_POST['forbiddenStuff'];
            }


    If($forbiddenInput){
        mysql_query("SET NAMES 'utf8'");
        $changeDataInDB = "UPDATE heroes_and_helpers SET forbidden='$forbiddenInput' WHERE name ='sabina'";
        mysql_query($changeDataInDB);

    }
?>

从数据库中提取:

   mysql_query("SET NAMES 'utf8'");
    $fetchForbidden = mysql_query("SELECT * FROM heroes_and_helpers WHERE name='sabina'");

        if (!$fetchForbidden)
          {
          die('Ngt ar fel: ' . mysql_error());
          }

    $whatIsForbidden = mysql_fetch_array($fetchForbidden); 
    $forbidden = $whatIsForbidden['forbidden'];

在网站上:

<textarea id="forbiddenField" style="width: 450px; height: 500px;"><?php echo $forbidden; ?></textarea>