简体   繁体   中英

How to send a Javascript Array and Form Input to PHP File (via $_GET for example)?

Let's say I have a basic form like:

<form enctype="text/plain" id="form" action="results.php" method="get">
<input type="checkbox" name="options[]" value="option1">
<input type="checkbox" name="options[]" value="option2">
<input type="checkbox" name="options[]" value="option3">
</form>

and a Global Javascript Array "arr" in the same File and obviously want to send them both to the results.php via GET or POST in order to use them with some php functions. Is there a simple way to achieve this, using only basic Javascript, HTML and PHP? (Well JQuery aswell I guess)

Thanks for your input :)

A simple way is to encode the array using JSON, and then add it to the serialized form.

$.post("script.php", $("#form").serialize + '&arr=' + encodeURIComponent(JSON.stringify(arr)), function(response) {
    ...
});

In PHP you would then decode the JSON:

$arr = json_decode($_POST['arr']);

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