LayUI & JQuery(Ajax) & PHP 練習 ~ 02_後端(PHP)接收由前端(JQuery Ajax)的JSON字串並透過後端(PHP)語法還原成對應物件 [jquery ajax object array to php]

LayUI & JQuery(Ajax) & PHP 練習 ~ 02_後端(PHP)接收由前端(JQuery Ajax)的JSON字串並透過後端(PHP)語法還原成對應物件 [jquery ajax object array to php]

LayUI & JQuery(Ajax) & PHP 練習 ~ 02_後端(PHP)接收由前端(JQuery Ajax)的JSON字串並透過後端(PHP)語法還原成對應物件 [jquery ajax object array to php]



GITHUB: https://github.com/jash-git/layui-jquery-php-example/tree/main/02


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>
			var myArray = [
			  { name: 'value1', age: 'value2' },
			  { name: 'value3', age: 'value4' }
			];

			// 將物件陣列轉換為 JSON 字串
			var jsonData = JSON.stringify(myArray);
		
            $.ajax({			
              url: './index_api.php',
			  type: 'POST',			
              dataType: 'json',			  
              data: { JsonInput: jsonData },
              
                  beforeSend: function(){
              },
              
              success: function(data) {
			    console.log('資料成功傳送到 PHP!');
                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');
    
    $jsonData = $_POST['JsonInput'];
    $dataArray = json_decode($jsonData, true); 
    
    $data = array();
    foreach ($dataArray as $obj) {
        $objectBuf = new stdClass();
        $objectBuf->name = $obj['name'];
        $objectBuf->age = $obj['age'];
        $data[] = $objectBuf;
    }
    $objectBuf01 = new stdClass();
    $objectBuf01->name = "jash.liao";
    $objectBuf01->age = "XX";
    $data[] = $objectBuf01;
    
    /*寫死回傳回傳物件
    $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;
?>

發表迴響

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