Pass an JavaScript object to a HIDDEN input field, and catch it as an array/object on the Server-Side
I have a field on my page, like this:
<input type="hidden" name="myField" id="myField" />
and I have a piece of code that looks like this:
$(document).ready(function() {
var myObject = {
item1: 'item1 value',
item2: 'item2 value',
item3: 'item3 value',
item4: 'item4 value',
};
$('#myField').val(myObject);
});
And when I submit 开发者_开发问答this form, I catch and ouput the $_POST
variable with print_r/var_dump functions and I get the following output for this Form Field (myField).
[myField] => [object Object]
How can I throw an JavaScript array/object to a form field and to have it evaluated/converted to a propper data-type on the server-side, so I could get it like this in my PHP script:
[myField] => Array(
item1 => item1 value
item2 => item2 value
item3 => item3 value
item4 => item4 value
)
How to achive this, without hard coding?
Encode the object as JSON [Wikipedia]:
$('#myField').val(JSON.stringify(myObject));
and decode it at the server side with json_decode
[docs].
The JSON
[docs] object is available in recent browsers and can also be included as library.
精彩评论