使用AJAX post将一组对象发送到服务器端

时间:2016-06-09 06:15:37

标签: javascript jquery ajax laravel laravel-5

以下是我的代码段。首先,我循环遍历每个表行,获取第一,第二和第三个文本并将其推送到名为'files'的数组(如多维数组,您可以看到它的控制台日志)

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>

然后使用Ajax post

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

然后在后端

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

如果我转储名为'id'的请求,这就是我得到的

  

array(3){[0] =&gt; array(4){[“name”] =&gt; string(18)“Name 1”[“age”] =&gt;   string(3)“22”[“identity”] =&gt; string(18)“Human”} [1] =&gt; array(4){   [ “名称”] =&GT; string(14)“Name 2”[“age”] =&gt; string(3)“18 [”identity“] =&gt;   string(14)“Human”} [2] =&gt; array(4){[“name”] =&gt;字符串(7)“名称3”   [ “年龄”] =&GT; string(3)“40”[“identity”] =&gt; string(7)“Alien”}}

但似乎不起作用,相反它给了我这个错误

  

尝试获取非对象的属性

请提供任何帮助,线索,想法,建议和建议吗?

1 个答案:

答案 0 :(得分:3)

$ count。= $ d =&gt;身份 $ count。= $ d [“身份”]

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