How can I post a JSON multi-dimensional data via Jquery.post?
How can I post a JSON multi-dimensional data via $.post? For instance, I have this multi-dimensional array in JSON format开发者_运维技巧:
{
"file":
{
"name" : "1024x768.jpg",
"type" : "image\/jpeg",
"tmp_name" : "C:\\wamp\\tmp\\php8F59.tmp",
"error":0,"size":469159
}
}
I will use Jquery.post()
to post the JSON data.
$.post("process.php",'{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}',function(xml){
});
So I can get this array in process.php
using print_r($_POST)
:
Array
(
[file] => Array
(
[name] => 1024x768.jpg
[type] => image/jpeg
[tmp_name] => C:\wamp\tmp\phpA1.tmp
[error] => 0
[size] => 469159
)
)
Is this possible?
Try this:
$.post("process.php",{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}},function(xml){
});
that should give you the desired array on the php side
Edit: this works since jQuery 1.4 and above
$jsonArray ='{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}';
$arr = JSON.stringify($jsonArray);
$.post("/url",{data:$arr},function(){
});
in the php file do
$json = json_decode($_POST['data']);
print_r($json);
Edit
may be this will help, i have not tested it though...
var file=[];
file["name"]="1024x768.jpg";
file["type"]="image/jpeg";
file["tmp_name"]="C:\wamp\tmp\phpA1.tmp";
file["error"]="0";
file["size"]="469159";
var myObject = new Object();
var enumm=["name","type","tmp_name","error","size"];
function getEnum(index){
return enumm[index];
}
$.each(file,function(i,j){
myObject[getEnum(i)]=file[getEnum(i)];
});
$.post("/url",{data:$.param(myObject)},function(xml){
});
on the php side do
$json = parse_str($_POST['data'], $data);
print_r($json);
精彩评论