【问题标题】:How store the data in Database from AJAX?如何从 AJAX 将数据存储在数据库中?
【发布时间】:2020-10-25 14:42:54
【问题描述】:

下面是我的一段代码。

$.ajax({
 type:'POST',
 dataType: JSON,
 url: 'http://localhost/UPLOAD-THIS/public/api/place-order',
 data: {"order":[{"id":2,"restaurant_id":2,"item_category_id":1,"name":"Burger","price":"10.00","image":"/assets/img/items/1570619770Fblsy6snNM.png","is_recommended":1,"is_popular":1,"is_new":1,"desc":null,"placeholder_image":"/assets/img/items/small/1570619770Fblsy6snNM-sm.png","is_active":1,"addon_categories":[],"quantity":1},
       {"id":3,"restaurant_id":2,"item_category_id":1,"name":"Pizza","price":"20.00","image":"/assets/img/items/1570619787yieN7hwXCQ.jpg","is_recommended":1,"is_popular":1,"is_new":1,"desc":null,"placeholder_image":"/assets/img/items/small/1570619787yieN7hwXCQ-sm.jpg","is_active":1,"addon_categories":[],"quantity":1}],
           "coupon":[],"location":"Campus","order_comment":null,"total":{"productQuantity":2,"totalPrice":30},"method":"Wallet","payment_token":""},
 success: function(e) {
   alert(success);
 },
 error: function(e) {
  alert(JSON.stringify(e));
 }
});

以上数据是虚拟的。 我想知道如何以将数据存储在数据库中的方式传递数据。

例如:“id”应从填写并存储在数据库中的表单中获取。

【问题讨论】:

  • 那么,您是在寻求从表单中提取数据的帮助,还是在将数据存储在数据库中的帮助?
  • 您需要在文件UPLOAD-THIS/public/api/place-order/index.php 中使用$_POST 处理传入数据的一些代码。然后触发这个ajax并检查你的响应(你也使用success: function(e) {,所以变量是e,但是你尝试提醒success,这似乎是未定义的)。
  • console.log(data);首先你调试一下。
  • @PHP 我做了,我得到了我真正想要存储的数据。
  • @CatchAsCatchCan 将数据存储在数据库中。我只是想知道如何在语法上写“数据”字段,以便从填写的表格中引用数据

标签: javascript php html ajax laravel


【解决方案1】:

如何将数据 POST 到后端并将其存储在数据库中:

您需要:

  1. 使用JavaScript从前端提取数据
  2. 将其包含在您的 POST 请求中。
  3. 捕获并处理PHP 中的请求,将其存储在数据库中。

示例:

这是一个单独的 PHP 文件示例(没有整页刷新), 但是您可能需要更改零件YOUR_DATA_HEREDATABASE_NAME_HEREroot(这是 PhpMyAdmin 中的用户名)。

<?php
if (isset($_POST['submit'])) {
  // Escape possible HTML tags:
  $content = htmlspecialchars($_POST['myContent'], ENT_QUOTES | ENT_SUBSTITUTE);

  // Database connection.
  // (Allows data to take 64 KB using "65536" constant)
  $db = new PDO('mysql:dbname=DATABASE_NAME_HERE', 'root', '');
  $db->query('CREATE TABLE IF NOT EXISTS `my_table` (id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, text VARCHAR(65536))');

  // Storing new record.
  $query = $db->prepare('INSERT INTO my_table VALUES (NULL, :text)');
  $query->bindValue(':text', $content);
  if ($query->execute()) {
    $response = 'Successfully stored: ' . $content;
  }
  else {
    $response = 'Error: ' . join(' ', $query->errorInfo());
  }

  exit($response);
}
?>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $('form#my_form_id').submit(function(e) {
      e.preventDefault();

      var myContent = "YOUR_DATA_HERE";
      var url = '#';
      $.post(url, {'submit': true, 'myContent': myContent}, function(response) {
        alert(response);
      });
    });
  });
</script>
</head>
<body>

<div id="center" style="text-align: center; margin-top: 150px;">

    <form id="my_form_id">
        <input type="submit" name="Send">
    </form>
</div>

</body>
</html>

注意事项:

  1. $.post(...) 方法是 $.ajax({type:'POST', ...}) 的简写(它们都是 AJAX)。
  2. 如果您想存储数据而不做任何更改,请删除 htmlspecialchars(...) 方法用法(例如 $content = $_POST['myContent'];)。

【讨论】:

  • 我认为这行不通,因为我想为我的项目使用 AJAX 调用方法。谢谢
  • 很抱歉造成混淆,但$.post(...) 方法是$.ajax({type:'POST', ...}); 的简写(它们都是AJAX)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多