简体   繁体   中英

Send an array of objects to the server side using AJAX post

Below is my snippet. First, I loop through each table row, get the first, second and third text and push it to the array named 'files' (like multi dimensional array, you can see its console log)

 var files = [] $(document).ready(function(){ $('table tr').each(function(){ files.push({ 'name' : $(this).find('td:first-child').text(), 'age' : $(this).find('td:nth-child(2)').text(), 'identity' : $(this).find('td:nth-child(3)').text() }); }); console.log(files); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Name 1</td> <td>22</td> <td>Human</td> </tr> <tr> <td>Name 2</td> <td>18</td> <td>Human</td> </tr> <tr> <td>Name 3</td> <td>40</td> <td>Alien</td> </tr> </table> 

and then send it using Ajax post

$.ajax({
    url:'/page.php',
    type:'post',
    dataType:'json',
    data: { id : files },
    success:function(e){}
});

and then in the back end side

public function rr(Request $request){
    $count = '';
    //loop
    foreach($request->id as $d){
       $count.=$d->identity;
    }
    dd(var_dump($count));
}

If I dump the request named 'id' here's what I get

array(3) { [0]=> array(4) { ["name"]=> string(18) "Name 1" ["age"]=> string(3) "22" ["identity"]=> string(18) "Human" } [1]=> array(4) { ["name"]=> string(14) "Name 2" ["age"]=> string(3) "18 ["identity"]=> string(14) "Human" } [2]=> array(4) { ["name"]=> string(7) "Name 3" ["age"]=> string(3) "40" ["identity"]=> string(7) "Alien" } }

but seems like its not working, instead it gives me this error

Trying to get property of non-object

Any help, clues, ideas, suggestions, recommendations please?

$count.=$d=>identity to $count.=$d["identity"]

  public function rr(Request $request){
    $count = '';
   //loop
    foreach($request->id as $d){
      $count.=$d["identity"];
   }
    dd(var_dump($count));
 }

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