一尘不染

键入时将值插入数据库

jsp

我有一个任务。我想在文本框中键入值时将数据插入数据库中。即使我也不知道这是可能的。任何示例将不胜感激。

提前致谢


阅读 212

收藏
2020-06-10

共1个答案

一尘不染

是的,有可能做到这一点。这是您的示例,但采用PHP方式。您可以使用此引用转换为JSP。

HTML

<input type="text" id="hey">

jQuery的

$('#hey').on('keyup', function(){    
   $.ajax({
      type : 'POST',
      url : 'insertData.php', // --> server side code to insert data into db
      data : {
        val : $(this).val()
      },
      success : function(msg){
        // msg -> return by server side
        // any code in success
        // if success will print out this 'New record created successfully'
        // if error will print out this 'Error occured'
        console.log(msg);
      }
  });
});

PHP-insertData.php

 <?php
 $servername = "localhost";
 $username = "username";
 $password = "password";
 $dbname = "myDB";

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);

 $sql = "INSERT INTO comment (myText)
 VALUES (".$_POST['val'].")";

 if ($conn->query($sql) === TRUE) {
   echo "New record created successfully";
 } else {
   echo "Error occured";
 }

 $conn->close();
 ?>
2020-06-10