简体   繁体   中英

send JavaScript array through jQuery AJAX POST

What I want to do is send an JavaScript Array to a PHP file.
This is what I got:

var mydata = [];
        console.log(document.getElementsByTagName("input")[0].name);
        for (var i = 0; i < document.getElementsByTagName('input').length; i++) {
            mydata[document.getElementsByTagName("input")[i].name] = document.getElementsByTagName("input")[i].value;
        };
        for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
             mydata[document.getElementsByTagName("select")[i].name] = document.getElementsByTagName("select")[i].value;
        };
        console.log(mydata);

        $.ajax({
            method: "POST",
            url: "q.php",
            data: {'lol': JSON.stringify(mydata)},
            contentType: 'application/json',
            dataType: 'json'
        })
        .done(function( msg ) {
            alert( "Data Saved: " + msg );
            $('#debug').html(msg);
        });

So as you can see, I create an array with a loop, at that moment all is fine. The problem is when I try to sent it through POST with JSON. I don't know if this is the best method...

I tried without JSON.stringify(); but the $_POST still empty

It seems like the post isn't sent, but I can see in the console the XHR post request has been sent.

Try to use this code and see the changes.

remove the contentType: 'application/json', dataType: 'json'

And change var mydata = [] into var mydata = {}

your ajax should look like this

$.ajax({
            method: "POST",
            url: "q.php",
            data: {'lol': mydata}
        })
        .done(function( msg ) {
            alert( "Data Saved: " + msg );
            $('#debug').html(msg);
        });

You dont have to stringify your mydata because you already decleared it as object.

Hope it helps

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