Ajax调用在json数据类型

时间:2018-01-11 09:21:38

标签: json ajax pdo

我试图使用ajax调用将ck-editor的数据插入到Mysql表中。 Mysql表中列的数据类型是文本,表中只有一列名为disclaimer。

文件index.php有一个ck编辑器和一个用于点击ajax调用的按钮。

的index.php

<html>
<script type="text/javascript">

  function disclaimerData() {
    var disclaimer=$("#disclaimer").val();


// AJAX code to send data to php file.

        $.ajax({
            type: "POST",
            url: "disclaimer-data.php",
            data: {disclaimer:disclaimer},
            dataType: "JSON",
            success: function(data) {
             $("#message").html(data);
            $("p").addClass("alert alert-success");
            },
            error: function(err) {
            alert(err);
            }
        });

}

  </script>
<body>
   <textarea id="js-ckeditor" class="disclaimer"  name="disclaimer"> </textarea>
 <button type="button" class="btn btn-square btn-secondary" name="insert-data" id="insert-data" onclick="disclaimerData()" style="background-color:#8C489F;color: white;cursor: pointer; ">Save</button>
</body>
</html>

文件disclaimer-data具有PDO脚本以将数据插入表中。

声明-data.php

<?php

 include('../includes/config.php');


$disclaimer = $_POST['disclaimer'];

$stmt = $db->prepare("INSERT INTO disclaimer(disclaimer) VALUES(:disclaimer)");

$stmt->bindparam(':disclaimer');

if($stmt->execute())
{
  $res="Data Inserted Successfully:";
  echo json_encode($res);
}else {
  $error="Not Inserted,Some Probelm occur.";
  echo json_encode($error);
}



 ?>

?>

上面代码中的问题是它在ajax调用上返回[Object Object]。

1 个答案:

答案 0 :(得分:0)

将您的HTML代码编辑为:

<?php
include('../includes/config.php');
$disclaimer = $_POST['disclaimer'];
$stmt = $db->prepare("INSERT INTO disclaimer(disclaimer)   VALUES(:disclaimer)");
$stmt->bindparam(':disclaimer');
$res = array();
if($stmt->execute())
{
    $res['msg']="Data Inserted Successfully:";
    $res['err'] = 0;
}
else 
{
    $res['msg']="Not Inserted,Some Probelm occur.";
    $res['err'] = 1;
}
echo json_encode($res);
?>

将您的脚本编辑为:

$.ajax({
        type: "POST",
        url: "disclaimer-data.php",
        data: {disclaimer:disclaimer},
        dataType: "JSON",
        success: function(data) {
         if(data.err==0){
             $("#message").html(data.msg);
             $("p").addClass("alert alert-success");
         }
         else{
            alert(data.msg);
         }

        }
    });