如何使用刀片模板和Laravel发送数据数组?

mzillmmw  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(134)

我想把下面部分的数据作为一个数组发送到Laravel后端。有没有一种方法可以不使用字符串化来完成这个任务?

// preferred output

$members = [
    ["name" => "Sam", "location" => "US"  ],
    ["name" => "Mike", "location" => "UK" ]
  ];
km0tfn4u

km0tfn4u1#

假设您有一个每行都有select和location的窗体。

  • 第一次循环并将所有值推入一个数组
  • 然后使用JSON.stringfy()将数据转换为JSON格式

以下是示例代码段:

var data = [];
document.querySelector("#submitForm").addEventListener("submit", (e) => {
   e.preventDefault();
    
   document.querySelectorAll(".member_name").forEach((member,index) => {
      let name = member.value;
      let location = member.nextElementSibling.value;
      data.push({name: name, location: location});
   });

   // Convert data into JSON format
   data = JSON.stringify(data);
   console.log(data);
      
   // Send Data to backend
});
<form action="submit" method="post" id="submitForm">
  <div>
    <select name="member_name" class="member_name">
      <option value="member1" selected>Member 1</option>
      <option value="member2">Member 2</option>
      <option value="member3">Member 3</option>
    </select>
    <select name="member_location" class="member_location">
      <option value="location1" selected>Location 1</option>
      <option value="location2">Location 2</option>
      <option value="location3">Location 3</option>
    </select>
  </div>
  <div>
    <select name="member_name" class="member_name">
      <option value="member1">Member 1</option>
      <option value="member2">Member 2</option>
      <option value="member3">Member 3</option>
    </select>
    <select name="member_location" class="member_location">
      <option value="location1">Location 1</option>
      <option value="location2">Location 2</option>
      <option value="location3">Location 3</option>
    </select>
  </div>
  <div>
    <select name="member_name" class="member_name">
      <option value="member1">Member 1</option>
      <option value="member2">Member 2</option>
      <option value="member3">Member 3</option>
    </select>
    <select name="member_location" class="member_location">
      <option value="location1">Location 1</option>
      <option value="location2">Location 2</option>
      <option value="location3">Location 3</option>
    </select>
  </div>
  <input type="submit" value="Submit">
</form>

你可以根据自己的意愿调整html中的错误和其他有无blade语法的内容。

ia2d9nvy

ia2d9nvy2#

像下面这样构造你的html表单

<select name="members[0][name]">

<input type="text" name="members[0][location]">

等等
members[index][name]中的索引将是动态的,并增加1
在你的controller函数中,你会得到members数组,如下所示:

dd($request->members);

相关问题