简体   繁体   中英

How to send JavaScript array using AJAX to PHP?

I want to send a JavaScript array to the server when a user clicks on a button.

My current code is as follows, but it does not work, could someone help me with this?

HTML

<?
    $arrs = {include for database}
    $js_array = json_encode($arrs);
?>
<script>
    var dataArray = <?php echo $js_array; ?>;
    var jsData = JSON.stringify(dataArray);
    $.ajax({
        type: "POST",
        url: "savepos.php",
        datatype: "JSON",
        data: {data : jsData},
        success: function() {
            alert('success!');
        }
    });
</script>

savepos.php

$data_array = json_decode(stripslashes($_POST['data']));

However, I get $data_array as null ?

You can just send the array without using JSON.stringify(). There is no need for it, as you set the datatype. Check out this fiddle

Open up chromes network tools before you hit run to see the form data being sent. Then you can use

<?php json_decode($_POST['data']); ?>

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