[英]How to access JSON array in PHP
我試圖通過ajax將多部分數組傳遞給PHP函數。
這是我的JS:
var datastring = {
newEmailForm: newEmailForm,
properties: properties
};
//got the data, make the ajax request
jQuery(function(){
jQuery.ajax({
type:'POST',
data:{
action: 'elegantSendEmail',
datastring: datastring
},
url: ajaxurl
})
})
這是要發送的數組:
action elegantSendEmail
datastring[newEmailForm][0][] {…}
0 email
1 title
2 Message
datastring[properties][0][] {…}
0 31466
1 value1
2 value1
datastring[properties][1][] {…}
0 31440
1 value2
2 value2
這是我嘗試通過PHP進行嘗試的嘗試,但我的響應中什么也沒有。
function elegantSendEmail(){
var_dump($_POST);
wp_die();
}
這是從控制台進行轉儲的結果:
array(2) {
["action"]=> string(16) "elegantSendEmail"
["datastring"]=> array(1) {
["newEmailForm"]=> array(1) {
[0]=> array(3) {
[0]=> string(5) "email"
[1]=> string(5) "title"
[2]=> string(17) "Youe message here"
}
}
}
}
$obj = json_decode($_POST['datastring']['newEmailForm'][0], true);
嘗試這個
function elegantSendEmail() {
$obj = $_POST['datastring']['newEmailForm'][0][0];
var_dump($obj);
//Above dump shows 'email'
wp_die();
}
您需要在ajax中以正確的json格式發送數據。 例如
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
因此,根據您的答案以及$_POST
結果在var_dump
之后,我們看到您傳遞了一個數組而不是json對象。 因此,您可以像訪問普通數組一樣訪問它的字段。
$obj=$_POST['datastring']['newEmailForm'][0][0] // will get you the email
$obj=$_POST['datastring']['newEmailForm'][0][1] // will get you the title
$obj=$_POST['datastring']['newEmailForm'][0][2] // will get you the message
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.