简体   繁体   中英

Using javascript to send an object through a form

I'm stuck trying to pass an object to another page , using javascript. I hope you can give me a hand . Thanks.

Here the object created and sent through a form and input.

var cars = {nombre : "luis", apellido: "heya"};

var form = '<form action="RegisterOrder.php" method="post">'+'<input type="hidden" name="arrayDatosProductos" value="'+cars+'"></input>'+'</form>';
$(form).submit();

In the page that receives the object :

var a = new Object(<?php echo $_REQUEST['arrayDatosProductos']; ?>);
alert(a.nombre);

JavaScript

var cars = {nombre : "luis", apellido: "heya"};

var form = '<form action="RegisterOrder.php" method="post">'
    + '<input type="hidden" name="arrayDatosProductos" value="'
    + String( JSON.stringify(cars) )
    + '"></form>';
$(form).submit();

PHP

var a = <?= $_REQUEST['arrayDatosProductos']; ?>;
alert(a.nombre);

I am not sure about the jQuery stuff, submitting a form created in JavaScript, but you need to convert the object cars to JSON and have it echoed in PHP into the new variable.

Well, after several attempts I could solve my problem , the last was by quotation marks (""), well, I stay this way :

var cars = {nombre : "luis", apellido: "heya"};
var ll = JSON.stringify(cars);

var form = '<form action="RegisterOrder.php" method="post">'
+'<input type="text" name="arrayDatosProductos" value='
+String(ll)+'></input>'+'</form>';

$(form).submit();

Y por ultimo:

var a = <?php echo $_REQUEST['arrayDatosProductos']; ?>;
alert(a.nombre);

I hope it will help someone in the future :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM