jquery ajax object array to php

jquery ajax object array to php

jquery ajax object array to php


資料來源: bard


01.Create an array of objects in JavaScript [JS建立物件陣列]

const data = [
  { id: 1, name: 'John Doe', email: 'johndoe@example.com' },
  { id: 2, name: 'Jane Doe', email: 'janedoe@example.com' },
  { id: 3, name: 'Peter Jones', email: 'peterjones@example.com' },
];


02.Send the array of objects to PHP using jQuery AJAX [AJAX傳送JSON字串給PHP]

$.ajax({
  url: 'process.php',
  method: 'POST',
  data: { data: data },
  dataType: 'json',
  success: function(response) {
    console.log('Response:', response);
  },
  error: function(error) {
    console.error('Error:', error);
  }
});


03.Process the array of objects in PHP[PHP將JSON字串轉成物件陣列]

<?php
$data = json_decode($_POST['data'], true);

foreach ($data as $item) {
  $id = $item['id'];
  $name = $item['name'];
  $email = $item['email'];

  // Process the data here
  echo "ID: {$id}, Name: {$name}, Email: {$email}<br>";
}
?>

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *