简体   繁体   English

使用jQuery更新文本区域

[英]update text area using jquery

I am trying to update data using jquery but it fails in case of textarea having enter in it, which is represented by \\r\\n in mysql. 我正在尝试使用jquery更新数据,但是如果输入了textarea,它会失败,这在mysql中由\\ r \\ n表示。

my code for update function is. 我的更新功能代码是。

<td><i class="fa fa-edit" onclick="upd('<?php echo $fetch_news ['title']; ?>',
                                                          '<?php echo $fetch_news ['detail']; ?>',
                                                          '<?php echo $fetch_news ['date']; ?>',
                                                          '<?php echo $fetch_news ['id']; ?>'
                                                          )"></i></td>

and my update function is 我的更新功能是

function upd(title,detail,date,id)
{
  $("#newsTitle").val(title);
  $("#newsDetails").val(detail);
  $("#newsDate").val(date);
  $("#id").val(id);
}

my text area input is 我的文本区域输入是

<div class="form-group"><textarea id="newsDetails" name="newsDetails" title="News Location (less than 200 words)" placeholder="News Details (less than 200 words)" required="" class="form-control"></textarea></div>

this code works fine if there is no enter pressed while inserting textarea data 如果在插入文本区域数据时没有按回车键,则此代码可以正常工作

the error i get is 我得到的错误是

Uncaught SyntaxError: Invalid or unexpected token

my insert function is 我的插入功能是

$(function () {
      $("#form").on("submit", function(){
            $.ajax({
                url: "extra/logical.php?pg=news&tsk=ins",
                type: 'POST',
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                  $("#showdata").html(data);
                  $("#newsTitle").val('');
                  $("#newsDetails").val('');
                  $("#newsDate").val('');
                  $("#id").val('');
                }
            });
            return false;
        });
    });

and insert query is 并插入查询是

$ins="insert into news set title='".$_POST['newsTitle']."',
                                        detail='".$_POST['newsDetails']."',
                                        date='".$_POST['newsDate']."'
                                        ";
        mysqli_query($conn,$ins);

Any help will be appreciated. 任何帮助将不胜感激。

You can prevent the default action of pressing enter in the textarea with an event listener. 您可以阻止使用事件监听器在textarea中按Enter的默认操作。

 <textarea placeholder="You can not press enter"></textarea> <script> document.querySelector("textarea").addEventListener("keypress", function(e){ if(e.keyCode==13){ e.preventDefault(); } }); </script> 

On the server-side, with PHP, you should replace all the line breaks with an empty String so the insertion will not fail (from this answer). 在服务器端,使用PHP,应将所有换行符替换为空的String,这样插入不会失败(根据答案)。

str_replace("\r\n", "", "your insertion statement string");  

First of all, @epascarello is correct in stating that you need to escape all data going into your database. 首先,@ epascarello正确地说您需要对进入数据库的所有数据进行转义。 You are also doing it in an extremely unsafe way, guaranteed to be hacked. 您还以一种非常不安全的方式来进行此操作,这肯定会被黑客入侵。 Creating your SQL-statements that way opens your code up for something called SQL Injection, and is probably the most common way a website is hacked. 以这种方式创建SQL语句可以打开称为SQL Injection的代码,这可能是网站被黑客入侵的最常见方式。

You need to use prepared statements and safeguard your code saving the data, as well as encode the data going in. 您需要使用准备好的语句并保护您的代码以保存数据,并对输入的数据进行编码。

As per the examples in this guide and the explanations given there, PDO is the only safe way to handle user input that is being saved to a database. 根据本指南中的示例以及此处给出的说明,PDO是处理保存到数据库的用户输入的唯一安全方法。 This is because of the way the prepared statements are prepared on the database server, before you put your data into the query. 这是由于在数据库服务器上准备预处理语句,你把你的数据在查询之前的状态。

As for code, look at this for saving the data: 至于代码,请看以下代码以保存数据:

$host = 'localhost';
$db   = 'myDatabase';
$username = 'awesomeUser';
$pass = 'someTotallySecretPassword';
$charset = 'utf8';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

$opt = [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];

$pdo = new PDO($dsn, $username, $password, $opt);
$stmt = $pdo->prepare('INSERT INTO news SET title = :title, details = :details, date = :date');
$stmt->execute([
    'title' => urlencode($_POST["newsTitle"]), 
    'details' => urlencode($_POST["newsDetails"]),
    'date' => $_POST["newsDate"]
]);
$user = $stmt->fetch();

I am going to advice you to also create the date yourself, on the server, either in SQL or in PHP, unless your use case needs the user to be able to insert a date different than the creation time of the news-article you are creating. 我建议您也可以在服务器上用SQL或PHP自己创建日期,除非您的用例需要用户能够插入与您所创建的新闻文章不同的日期。创建。 If the user does have a need to insert an arbitrary date, you need to do some validation on that as well, to make sure it is valid. 如果用户确实需要插入一个任意日期,则还需要对此进行一些验证,以确保该日期有效。

Now, when you need to get the data out again, you need to decode the data from the database with javascript: 现在,当您需要再次获取数据时,需要使用javascript解码数据库中的数据:

function decode(text)
{
    return decodeURIComponent(text.replace(/\+/g,' '));
}

function upd(title,detail,date,id)
{
  $("#newsTitle").val( decode(title) );
  $("#newsDetails").val( decode(detail) );
  $("#newsDate").val( date );
  $("#id").val( id );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM