簡體   English   中英

構建HTML表單輸出

[英]Structuring HTML form output

我有一個帶有JSON輸出的HTML表單,其結構如下:

<form>
  <input name="a1">
  <input name="a2">
  <input name="a3">
  <input name="b1">
  <input name="b2">
  <input name="b3">
  <input name="c1">
  <input name="c2">
  <input name="c3">
</form>
{
  "a1": "some value",
  "a2": "another value",
  "a3": "yet another value",
  "b1": "some value",
  "b2": "another value",
  "b3": "yet another value",
  "c1": "some value",
  "c2": "another value",
  "c3": "yet another value"
}

但我希望將其排序為:

{
  "a": {
    "1": "some value",
    "2": "another value",
    "3": "yet another value"
  },
  "b": {
    "1": "some value",
    "2": "another value",
    "3": "yet another value"
  },
  "c": {
    "1": "some value",
    "2": "another value",
    "3": "yet another value"
  }
}

我的問題: 在HTML中 ,有沒有一種方法可以構造表單以使JSON輸出在發送到服務器時像這樣顯示? 我正在為服務器使用NodeJS。 讓我知道您是否需要更多信息。

就像您一樣,這就是我們在React項目中使用的方式。 只需創建JSON對象並將其存儲在數據庫中的任何位置,

例:

  orderForm: { name: { elementType: 'input', elementConfig: { type: 'text', name: 'name', placeholder: 'Your Name' }, value: '', label: 'Name', }, street: { elementType: 'input', elementConfig: { type: 'text', name: 'street', placeholder: 'Street' }, value: '', label: 'Street', }, zipCode: { elementType: 'input', elementConfig: { type: 'text', name: 'zipCode', placeholder: 'Zip Code' }, value: '', label: 'Zip Code', }, country: { elementType: 'input', elementConfig: { type: 'text', name: 'country', placeholder: 'Country' }, value: '', label: 'Country', } }, 

注入HTML,您可以猜測一下,這就是我們創建動態表單以從用戶獲取數據的方式。

 const formElementsArray = []; for (let key in this.state.orderForm) { formElementsArray.push({ id: key, config: this.state.orderForm[key] }); } {formElementsArray.map(formElement => ( <Input key={formElement.id} {...formElement.config} />} 

注意:如果發現任何問題,只需包裝控制台,即可獲得此問題。

開心!

你可以這樣寫

<form>
  <input name="a.one">
  <input name="a.two">
  <input name="a.three">
  <input name="b.one">
  <input name="b.two">
  <input name="b.three">
  <input name="c.one">
  <input name="c.two">
  <input name="c.three">
</form>

你會得到一個這樣的對象

{
  "a": {
    "one": "some value",
    "two": "another value",
    "three": "yet another value"
  },
  "b": {
    "one": "some value",
    "two": "another value",
    "three": "yet another value"
  },
  "c": {
    "one": "some value",
    "two": "another value",
    "three": "yet another value"
  }
}

希望這可以幫助。 讓我知道您是否還有其他問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM