Pass PHP Array via jQuery Ajax

后端 未结 5 978
粉色の甜心
粉色の甜心 2021-01-22 13:40

I\'ve got a php array:

$toField = explode(\",\", $ids);  //Which looks something like \'24,25,26,29\'

I want to pass this array via jQuery AJAX

相关标签:
5条回答
  • 2021-01-22 13:56
    <form id='myform'>
     <input type='hidden' name='to[]' value='1' />
     <input type='hidden' name='to[]' value='2' />
    
     .. etc ..
     .. rest of you're form ..
    </form>
    

    jQuery change the data: .. part to:

    data: $('#myform').serialize()
    

    Then in you're PHP:

    foreach ( $_POST [ 'to' ] as $num )
    {
     // do something with $num;
    }
    

    Something like this an option?

    0 讨论(0)
  • 2021-01-22 13:57

    Few things going on I'd sort out:-

    • You're missing the id 'toField' on your toField input element.

    • You should be using implode() on the $id variable rather than exploding it.

    • On the otherside you should be calling explode() on the recieverId string.

    0 讨论(0)
  • 2021-01-22 14:07

    First, you probably want to use implode, and not explode, to construct your $toField variable ;-)

    $ids = array(24, 25, 26, 29);
    $toField = implode(',', $ids);
    var_dump($toField);
    

    Which would give you

    string '24,25,26,29' (length=11)
    

    You then inject this in the form ; something like this would probably do :

    <input type="hidden"  value="<?php echo $toField; ?>">
    

    (Chech the HTML source of your form, to be sure ;-) )


    Then, on the PHP script that receives the data from the form when it's been submitted, you'd use explode to extract the data as an array, from the string :

    foreach (explode(',', $_POST['receiverID']) as $receiverID) {
        var_dump($receiverID);
    }
    

    Which will get you :

    string '24' (length=2)
    string '25' (length=2)
    string '26' (length=2)
    string '29' (length=2)
    

    And, now, you can use thoses ids...

    0 讨论(0)
  • 2021-01-22 14:07

    you can get the string in the php code and separate it on the comma, then loop through the values.

    http://us3.php.net/split

    0 讨论(0)
  • 2021-01-22 14:12

    just echo your array in a for each loop with some special characters like | &| . if it is multi dimensional use each character on both loops and echo it. and by using some delimiter function change it back to array in java script

    0 讨论(0)
提交回复
热议问题