Send a multi dimensional array via $.post using jquery
I have a global variable I'm using to store a bunch of information in a project I'm working on. It is an object with various values and I guess other objects in it. For example...
$.myVar {
currentProj : "Project 1",
allProjs : [],
toggleVar : 0
}
Now as the program runs and I do things, I'm actually adding arrays within allProjs. I want to use the array index as the name of the project, and then it contains a bunch of information. Here is a sample of what the object looks like after running the program for a few minutes.
(copied from Chrome's console):
开发者_如何学JAVA$.myVar
Object
currentProj: "McB2"
toggleVar: 0
allProjs: Array[0]
McB1: Array[0]
length: 0
__proto__: Array[0]
McB2: Array[4]
0: "02070124"
1: "02030036"
2: "02090313"
3: "02090450"
length: 4
Now I want to pass this data to a PHP file using $.post so I can convert it to JSON and save it on the server.
I do this basically by just running:
$.post('saveJSON.php', $.myVar, function(data) {
$('#dumpspace').html(data);
});
For debugging I've got the PHP file just outputting:
print_r($_REQUEST);
Now I would expect a multi-dimensional array that I could convert to JSON and then save, but all it is spitting out is:
Array ( [currentProj] => McB2 [toggelVar] => 0 )
So I can see that it's not sending the the allProj section of the object, but I'm not sure why! It does seem to show up when I look at the object in the console, so I'm not sure what I'm missing.
Any help is appreciated.
Thanks!
Clarification
The first section, where I declare allProjs, is it possible I'm doing something wrong there? When I run Stringify, I end up with a similarly wrong result:
JSON.stringify($.myVar)
"{"currentProj":"McB2","allProjs":[],"toggleVar":0}"
You need to .stringify
the object / array into a JSON string. All "modern" browsers do support this natively with JSON.stringify(obj)
. If you need to support "older" browser version aswell, you need to go to http://www.json.org and download the json2.js
lib which offers the same functionality.
The other way around, if you want to receive a JSONized string from a server, you need to either tell jQuery that you're expecting a json string by passing 'json' into your $.post()
call, or you need to parse the received data yourself by again accessing the JSON
object. JSON.parse(json_string)
will return a Javascript object from a passed in JSON string.
Figured out my problem. When I was declaring the object originally I was making allProj and Array by putting in []. If I put it in as allProj : {}, then it works perfectly! Thanks for the suggestions, helped narrow down my mistake.
-M
I believe you must first convert your array to the JSON format before posting to PHP.
This is the method I have used in the past:
var jsonOb = JSON.stringify(yourArray);
$.post(
"yourPage.php",
{jsonOb:jsonOb},
function(r){
//your success response
}
);
Hope this does the trick brother!
W.
精彩评论