簡體   English   中英

如何將 AJAX 中的數據存儲在數據庫中?

[英]How store the data in Database from AJAX?

下面顯示了我的一段代碼。

$.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”應該從填寫並存儲在數據庫中的表單中獲取。

如何將數據 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']; )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM