简体   繁体   中英

Sending an array/set via to PHP via $.ajax. PHP adding a number

Im trying to send an array to the PHP script:

usedAnswers = [1,2];

    // funtion for displaying a question
    displayQuestion = () => {

        $.ajax({
            url: "backend/retriveData.php",
            data: {usedAnswers:usedAnswers} ,
            type:"post",
            success: function(response) {
                console.log(response);
            }
        });
    }

    // inital display of question
    displayQuestion();

Then when I want to access the array in the PHP script

<?php
echo print_r($_POST['usedAnswers']);
?>

I get the following problem on screen

在此处输入图片说明

Why is he adding an extra 1 ?

When I try to access the first element of the Array like this:

echo print_r($_POST['usedAnswers'][0]);

He console.logs me the number 11?

What am I doing wrong what is the correct way to send an Array via Ajax?

Is it also possible to send a set via Ajax?

so, based on your comments, it appears your question is really referring to how to send data through, rather than the odd output you're getting, which Jay has already answered for you.

as far as your code reads, what you're actually sending is this:

{[1, 2]:[1, 2]}

which is invalid JSON.

if you're trying to actually have a 'usedAnswers' key (which it looks like from your php), then you need to do this:

        $.ajax({
            url: "backend/retriveData.php",
            data: {'usedAnswers':usedAnswers}, // <-- note the quotes around the key
            type:"post",
            success: function(response) {
                console.log(response);
            }
        });

Because you are echoing the print_r() (which in and of itself is a type of echo ) you're returning a value for the truthiness of the print_r() . Change the line to this

print_r($_POST['usedAnswers']);

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