我知道这个问题之前已经被问过,并且我已经阅读了一些建议和答案,但我无法让它发挥作用。
我在 php 页面上有一个文本区域,我想在用户输入时或每 2-5 秒将文本区域的内容保存到 SQL 数据库中,而无需重新加载页面。
我相信它必须用 jquery 和 Ajax 制作?
如果我将其作为带有保存按钮的 POST 表单,内容将保存到数据库中 - 所以我知道 sql 正在运行。
我有这些文件: 待办事项.php
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<form method='post' action='notes.php'>
<table border='0' cellspacing='0' width='480px' height='250px' align='center' id='logo-table'>
<tr>
<td align='center' height='10px' valign='top'><textarea type='text' id='notes_input' name='notes_input' style='width: 460px; height: 230px; border:0px;'>$data[notes]</textarea></td>
</tr>
</table>
<input type='image' src='/nycrm/grafik/Save-as.png' name='gem' value='Submit' />
</form>
和 script.php
<?php
require_once 'connect.php';
session_start();
$ses_userid = $_SESSION['ses_userid'];
$notes_input = $_POST["notes_input"];
mysqli_query($connect_intra, "UPDATE user SET notes = '$notes_input' where userid = '$ses_userid'");
?>
我尝试了在 stackoverflow 上找到的这段代码,但似乎代码没有被执行 - 在这种情况下,todo.php 看起来像这样:
<?php
$ses_userid = $_SESSION['ses_userid'];
$query = mysqli_query($connect_intra, "SELECT notes FROM user WHERE userid = '$ses_userid'");
$data = mysqli_fetch_array($query);
echo"
<script type=\"text/javascript\" src=\"//code.jquery.com/jquery-1.9.1.js\"></script>
<script type=\"text/javascript\">
$(\"#notes_input\").bind(\"keydown\", function() { myAjaxFunction(this.value); });
function myAjaxFunction(value) {
$.ajax({
url: \"script.php\",
type: \"POST\",
data: \"notes_input=\" + value,
success: function(data) {
if (!data) {
alert(\"unable to save file!\");
}
}
});
}
</script>
<form method='post' action='notes.php'>
<table border='0' cellspacing='0' width='480px' height='250px' align='center' id='logo-table'>
<tr>
<td align='center' height='10px' valign='top'><textarea type='text' id='notes_input' name='notes_input' style='width: 460px; height: 230px; border:0px;'>$data[notes]</textarea></td>
</tr>
</table>
<input type='image' src='/nycrm/grafik/Save-as.png' name='gem' value='Submit'/>
</form>
";
?>
我是否错过了一些东西,所以它会起作用?
非常感谢您的帮助。
/托马斯。
最佳答案
浏览器从上到下读取 HTML。当它找到脚本标签时,它会暂停解析并评估脚本。
在您的示例中,当第二个脚本启动时,textarea 还不存在。
由于jquery
找不到任何id为notes_input
的节点,它只是创建空的jquery对象以防止进一步函数中出现错误。
您应该将第二个脚本(带有 .bind
语句)移至 body
标记的末尾,或将出价包装到 jquery.ready
函数。它将延迟脚本的执行,直到页面完全解析。
关于php textarea使用jquery/ajax自动保存到sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37929629/