简体   繁体   中英

How do I send dynamic key pair values to PHP with jQuery?

I have some jQuery code that sends data to a PHP function, and some of the data that will be sent is key => value pairs.

The way I am doing it now is I am setting a variable to [] and then pushing {'string1':'string2'} , then sending this variable in.

So like this:

$(".test-button").click( function() {
        var inputData = [];
        $('.input-data').each(function( index ) {
            var name = $(this).attr("name");
            var value = $(this).val();
            inputData.push( { name : value } );
        });
var data = {
            testData: inputData
        };

When I get the data in PHP, if what I'm sending is 3 key value pairs, then the print_r output looks like this:

Array
(
    [0] => Array
        (
            [name] => 1
        )

    [1] => Array
        (
            [name] => 2
        )

    [2] => Array
        (
            [name] => 3
        )

)

What I'd really like is on the PHP side to just do something like

foreach($myInputData as $key => $value)
{
   $output .= $key . " : " . $value . " ";
}

I am a bit confused as to how to do this easy in jQuery/JavaScript

When creating your javascript object, name is being treated as a literal, it's not using the variable you defined previously. You can do inputData.push( { [name] : value } ); instead. This will create a new object each time and add it to the array, but you seem to be looking for a solution that sends just an object:

var inputData = {};
$('.input-data').each(function(index) {
  var name = $(this).attr("name");
  var value = $(this).val();
  inputData[name] = value;
});

can you try below code.

    $(".test-button").click( function() {
        var inputData = {};
        $('.input-data').each(function( index ) {
            var name = $(this).attr("name");
            var value = $(this).val();
            inputData[name] = value;
        });

    var data = inputData;

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