JS 部份
//ajax 傳送array 到php
var loginInfo = [];
var username = $("#username").val();
var password = $("#password").val();
loginInfo.push({"username": username, "password": password});
loginInfo = JSON.stringify(loginInfo); //將array轉成json形式
$.ajax({
type:"POST",
url:"target.php",
dataType:"json",
data:{loginInfo:loginInfo},
success:function(result){
console.log(result);
console.log(result.key1);
}
});
PHP 部份
//php 接收前台傳來的array
if(isset($_REQUEST['loginInfo']){
$loginInfo = json_decode($_REQUEST['loginInfo']); //將json形式decode
for($i = 0;$i < sizeof($loginInfo); $i++){
echo $loginInfo[$i]->username;
}
$array = array[
"key1" => "value1",
"key2" => "value2",
];
$array = json_encode($array); //以json形式encode
echo $array; //回傳$array
}