简体   繁体   中英

Sending array to PHP using XMLHttpRequest (pure JS)

I'm attempting to send an array from JS to PHP using AJAX.

What seems to be happening is that the request is going through and is successful, but no data is received on the server (my test.php script needs the data from this array). Here is what I have so far...

Javascript

myButton.onclick = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "test.php", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState==4 && xhr.status==200) {
            console.log("Done. ", xhr.responseText);
        }
    }

    //xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send('myArray='+JSON.stringify(myArray));
};

test.php

<?php
//$myArray = json_decode($_POST['myArray']); //Undefined index
print_r($_POST);

Note, myArray is not shown in the above code, but it is a valid array.

I've searched around SO (which led me to adding the 'setRequestHeader' in), as well as the wider internet. However, this has made no difference and I seem to be going round in circles. When I print $_POST, it's always an empty array.

I'm sure there's something I'm missing/misunderstanding.

Edit

As requested...

var myArray = ["John", "Jill", "James"];

I've also attempted this with an array of booleans, as well as an associative array/object.

Edit 2

As requested, adding screen shot from dev console...

在此处输入图片说明

you can use formData :

let data = new FormData();
let values = [1, 2, 3];
data.append('myArr', JSON.stringify(values));
// send data to server

and in php use json_decode :

$Values = json_decode($_POST['myArr']);

another way is to create HTML checkbox or select elements with javascript , assign values , serialize them and send them to back-end .

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