How do you post using jquery an associated array inside and array to a php script for proccessing
I am obtaining data from an api via xml which contains data about each user of a website. I need to ultimately save this data into a mysql database. I am parsing the data and obtaining the values for each user using jquery.
I am find the nodes for each user like so
$onlineid = $(this).find("onlineid");
$comment = $(this).find("comment");
and then obtaining the values..
var onlineid = $onlineid.text();
var comment = $comment.text();
This is where i am now stuck...
I need to create an associated array of users data and then add each users data to an array of users so that it can all be processed using php, then saved to mysql.
maybe 开发者_开发百科something like this..?
var users = new Array();
var user_data = new Object();
user_data['onlineid'] = onlineid;
user_data['comment'] = comment;
then..
users.push(user_data);
This seems to build an array of objects. If i post them to a php script like so using ajax
$.ajax({
type: "POST",
url: "sync.php",
data: 'users='+users
firebug shows them as a string of object separated by commas.
How on earth do i deal with that in the php script?
I basically need to process each object (user_data) in each of the array items (users) so that the values can be saved to a mysql database.
Any expert advice would be fantastic.
you break the "a string of object separated by commas" into pieces in PHP using explode:
$users_array = explode(",",$users);
Checkout this gist. It expands on the answer by @picus.
You could try to parse them out into a list of values in the qs that looks like this:
?users[]=user1&users[]=user2&users[]=user3
This should give you an array called users that is part of the POST request for your PHP page:
print_r($_POST['users']);
would output:
user1, user2, user3
I don't use PHP, but what I'd do is create a javascript object that is comprised of a single userid field/property and another field/property which holds a simple array of comments for that user (this permits multiple comments per user). Then I'd create a container to hold all of those objects, either a simple (numeric offset) array or an associative array using the userid (as a string) as the key. Then I'd JSONify the whole kit-and-caboodle and post the JSON-encoded string to the server where it would get decoded from JSON format back into objects the server could work with. PHP surely offers some helper methods to make this easy. I'd search for "PHP JSON".
I would transfer the data as a JSON-encoded string:
var users = [];
// in a loop:
users.push({onlineid: $(this).find("onlineid").text(),
comment: $(this).find("comment").text()});
// ajax request:
$.ajax({
type: "POST",
url: "sync.php",
data: {users: JSON.stringify(users)} // automatic HTTP encoding
The JSON
object is either built in or available via this script.
In PHP use json_decode
:
$users = json_decode($_POST['users'], true);
精彩评论