php object array to jquery ajax

php object array to jquery ajax

php object array to jquery ajax


資料來源: Bard


01.PHP Create an array of objects [PHP 建立物件陣列]

<?php
$data = array();
$object1 = new stdClass();
$object1->name = "John Doe";
$object1->age = 30;
$data[] = $object1;

$object2 = new stdClass();
$object2->name = "Jane Doe";
$object2->age = 25;
$data[] = $object2;

// Encode the array to JSON
$json = json_encode($data);
?>


02.PHP Send the JSON data [PHP 將物件陣列轉JSON字串]

<?php
header('Content-Type: application/json');

// Get the JSON data
$json = $data;

// Send the JSON data
echo $json;
?>


03.AJAX request to the PHP script that sends the JSON data [jQuery AJAX 接收 PHP 傳送的 JSON字串]

$.ajax({
  url: 'data.php',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  }
});
$.ajax({
  url: 'data.php',
  dataType: 'json',
  success: function(data) {
    for (var i = 0; i < data.length; i++) {
      console.log(data[i].name + ' - ' + data[i].age);
    }
  }
});

One thought on “php object array to jquery ajax

發表迴響

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