Tips:當你看到這個提示的時候,說明當前的文章是由原emlog部落格系統搬遷至此的,文章釋出時間已過於久遠,編排和內容不一定完整,還請諒解`
如何優雅的提交一個表單
日期:2019-5-6 阿珏 折騰程式碼 瀏覽:1734次 評論:1條
這是一個非常基礎的HTML表單提交問題,但卻是一個非常實用的技巧
我的業務場景是這樣的:
一個可動態建立input的表單,如下圖
這意味著input的name不能是一個固定的,要不然肯定會被覆蓋掉的
第一種,傳統的普通的提交方式,給每一個要提交的input一個唯一的name
<form id="form1" action="./index.php" method="get"> <div class="form-control"> <input type="text" name="name1" /> <input type="text" name="num1" /> <input type="text" name="img1" /> </div> <br> <div class="form-control"> <input type="text" name="name2" /> <input type="text" name="num2" /> <input type="text" name="img2" /> </div> <br> <div class="form-control"> <input type="text" name="name3" /> <input type="text" name="num3" /> <input type="text" name="img3" /> </div> ...... <input type="submit" value="Submit" /> </form>
瀏覽器提交抓到的格式是這樣子的

伺服器獲取列印出來的是這樣的,對後端的資料處理就非常不友好

第二種,陣列的方式進行表單提交
<form id="form1" action="./index.php" method="get"> <div class="form-control"> <input type="text" name="infos[1][name]" /> <input type="text" name="infos[1][num]" /> <input type="text" name="infos[1][img]" /> </div> <br> <div class="form-control"> <input type="text" name="infos[2][name]" /> <input type="text" name="infos[2][num]" /> <input type="text" name="infos[2][img]" /> </div> <br> <div class="form-control"> <input type="text" name="infos[3][name]" /> <input type="text" name="infos[3][num]" /> <input type="text" name="infos[3][img]" /> </div> ...... <input type="submit" value="Submit" /> </form>
瀏覽器和後端列印的分別為


細心觀察就回發現,提交的name值發生了變化,變成了一樣的 ?陣列?
提交到後端就回發現資料比之前整齊多了
但這裡要注意的是,提交的陣列鍵中不需要使用引號,要不然引號也會成為鍵的一部分
當然了,實際中還可能遇到這樣的問題,要提交的組數(像上面的1、2、3)是不確定的,可以在前端隨意的新增,這個時候怎麼去用陣列提交這些內容呢?
下面就是我業務中的實際解決方案

這樣的話,二維陣列的鍵則不需要我們自己去維護了,由瀏覽器幫我們自動生成

後端接收到的資料則變成了這樣子,變得非常好處理了

此方法適用於,要提交一堆不確定個數的一組有關的資料對
完結撒花!~
網友評論:
Railgun丶無限 2年前 (2019-05-21)
新技能已get√