LayUI & JQuery(Ajax) & PHP 練習 ~ 01_前端(JQuery Ajax)接收由後端(PHP)的JSON字串並透過前端(JS)語法還原成對應物件 [php object array to jquery ajax]
LayUI & JQuery(Ajax) & PHP 練習 ~ 01_前端(JQuery Ajax)接收由後端(PHP)的JSON字串並透過前端(JS)語法還原成對應物件 [php object array to jquery ajax]
GITHUB: https://github.com/jash-git/layui-jquery-php-example/tree/main/01
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="layui/css/layui.css"> </head> <body> <!-- body 末尾放置所有JS --> <script src="./js/jquery-3.7.1.js"></script> <script src="layui/layui.js"></script> <script> $.ajax({ url: './index_api.php', dataType: 'json', beforeSend: function(){ }, success: function(data) { var StrMsg=''; for (var i = 0; i < data.length; i++) { StrMsg+=data[i].name + ' - ' + data[i].age+'\n'; console.log(data[i].name + ' - ' + data[i].age); } alert(StrMsg); }, error: function() { }, complete: function() { } }); </script> </body> </html>
index_api.php
<?php header('Content-Type: application/json; charset=utf-8'); $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 $Strjson = json_encode($data); echo $Strjson; ?>