使用 ajax 保存文本区域“onkeypress”的内容


Save content of textarea "onkeypress" with ajax

我是Ajax请求的初学者,我被困住了:我想在数据库中保存一个文本区域,每次按键。

JavaScript

   $("#note_content").bind("keydown", function() {
        note(this.value)
   });
   function note(value) {
       $.ajax({
           async : false,
           type: "GET",
           url: "./ajax.php",
           data: {
             'block' : 'note', 
             'text'  : value
           },
           success: function(data) {
             $("#note_content").html(html);
           }
       });
   }

.PHP

<?php
header('Content-type: text/html; charset=utf-8');
 function note() {
   $bdd = new PDO('mysql:host=localhost;dbname="myDatabase";charset=utf8', 'root', 'password');
   $req = $bdd->prepare('UPDATE note set text= ?');
   $req->execute(array($_GET['text']);
   $reponse = $bdd->('SELECT text FROM note');
   $donnees = $reponse->fetch();
   $text = $donnees; 
   return($text)
}
if(($_GET['block'] == 'note'){
    echo note();
}
?>

使用JQuery,我正在收听文本区域的按键。当发生时,它会将按下的键传递给函数note()将参数传递给 PHP。它将文本保存在表格note并返回存储的文本。

我收到错误 500(内部服务器错误(,我不知道我的代码出了什么问题。也许是关于header('Content-type: text/html; charset=utf-8');哪些需要json内容类型?

知道我做错了什么吗?

在 ajax 相关 API 中,您需要使输出可读 javascript 并且需要将error_reporting设为 0,因此打印纯 JSON 输出,并且您的 javascript 可以轻松读取它......你可以这样做...

<?php
header('Content-type: application/json; charset=utf-8');
 function note() {
   $bdd = new PDO('mysql:host=localhost;dbname="myDatabase";charset=utf8', 'root', 'password');
   $req = $bdd->prepare('UPDATE note set text= ?');
   $req->execute(array($_GET['text']);
   $reponse = $bdd->('SELECT text FROM note');
   $donnees = $reponse->fetch();
   $text = $donnees; 
   return($text)
}
if(($_GET['block'] == 'note'){
    $output = array();
    $output['status'] = true;
    $output['error'] = 'no errors';
    $output['data'] = note();
    echo json_encode($output);
}else{
    $output = array();
    $output['status'] = false;
    $output['error'] = 'block is not note';
    echo json_encode($output);
}
?>

在JavaScript中,您可以像...

 success: function(data) {
         $("#note_content").html(data['data']);
       }