I am using the following jquery ajax call:
$(document).ready(function () {
submitAct();
function submitAct(){
var alldata = [];
alldata.push( {
"pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
"title": 'Fun with Gophers',
});
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: "data=" + JSON.stringify(alldata),
});
}
});
On the server, the result of $_POST[data] is showing as:
[{"pid":"d2a7d886-6821-3eaa-079f-fbe278c6a16a","title":"Fun with Gophers"}]
I am having trouble accessing the keys and related values of 'pid' and 'title'. Would someone please provide some insight? I've tried things like below but haven't had any success:
$_POST['title']
$data = json_decode( $_POST['data']);
$data->title
Thanks!
Several suggestions:
First you are enclosing the data object in an array, needlessly. To access it now:
$data = json_decode( $_POST['data']);
$data=$data[0];/* access object in array*/
$data->title;
The default content type for $.ajax is application/x-www-form-urlencoded; charset=UTF-8
application/x-www-form-urlencoded; charset=UTF-8
...exactly the same as sending a regular form. Think of each key in your data object as you would name
of a form control.
There is no need to JSON.stringify to send. jQuery will serialize objects and arrays for you
You can simply send it like this:
var alldata = {
"pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
"title": 'Fun with Gophers',
};
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: alldata
});
Then in php:
$title=$_POST['title'];
Change the data
part of the ajax request to the following:
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: {"data": JSON.stringify(alldata)},
});
Now you can access the sent content via $_POST["data"]
in the appropriate php file.
Example:
$json = json_decode($_POST["data"]);
var_dump($json[0]->{"title"}); // [0] because of the array
$a = json_decode($_POST['data']);
print_r($a[0]->pid);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.