[英]How to access JSON array in PHP
I am trying to pass a multiple part array via ajax to a PHP function. 我试图通过ajax将多部分数组传递给PHP函数。
This is my JS: 这是我的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
})
})
This is the array thats being sent: 这是要发送的数组:
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
Here is my attempt at trying to get at it via PHP but i just get nothing in my response. 这是我尝试通过PHP进行尝试的尝试,但我的响应中什么也没有。
function elegantSendEmail(){
var_dump($_POST);
wp_die();
}
Here is the result of the dump from my console: 这是从控制台进行转储的结果:
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);
Try this 尝试这个
function elegantSendEmail() {
$obj = $_POST['datastring']['newEmailForm'][0][0];
var_dump($obj);
//Above dump shows 'email'
wp_die();
}
You need to send data with proper json format in ajax. 您需要在ajax中以正确的json格式发送数据。 for example
例如
{
"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" }
]
}
So based on your answer and after var_dump
the $_POST
result we see that you pass an array and not a json object. 因此,根据您的答案以及
$_POST
结果在var_dump
之后,我们看到您传递了一个数组而不是json对象。 So you can access it's fields like a normal array. 因此,您可以像访问普通数组一样访问它的字段。
$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.