Home > Web Front-end > JS Tutorial > How to obtain multiple pieces of data in a form field and convert them into json format

How to obtain multiple pieces of data in a form field and convert them into json format

一个新手
Release: 2017-10-18 09:55:18
Original
1923 people have browsed it

As shown in the figure, we need to obtain the data in the following two li tags and then pass it to the backend; the data format received by the backend is json, so we need to convert the information in the two li In the following format.

{recieverName:Xiaohong,recieverPhone:12341234,recieverAddress:Hunan,China},{recieverName:Xiaoming,recieverPhone:12345678,recieverAddress:Shanghai, China}

The code is as follows:

var recieverArr = [];  //全局变量
var recieverMsg = {};  //全局变量
function recieverMsgToJson(parentFormId){    //若有多个表单公用这个函数,这里需要传所属表单的ID;例如新增和修改。
  $(parentFormId + ".recieverList li").each(function(m){    //遍历每个li,当前有两个li
      var recieverAttributes = [];
      $(this).find("span").each(function(n){    //遍历每个li下的span,而每个li下有三个span
         recieverAttributes[n] = $(this).children("input").val();   //找到每个span下存放着数据的input框,并获取值存放到数组中
      });
      var recieverObj = {    //用对象来表示数据;这时对象是{recieverName:小明,recieverPhone:12345678,recieverAddress:中国上海}
         receiverName:recieverAttributes[0],
         receiverPhone:recieverAttributes[1],
         receiverAddress:recieverAttributes[2]
      };
      recieverArr.push(recieverObj);       
  });
}
recieverMsg = JSON.stringify(recieverArr).replace(/\[|]/g, '') //将数组转化为json格式
console.log(recieverMsg)
//{recieverName:小红,recieverPhone:12341234,recieverAddress:中国湖南},{recieverName:小明,recieverPhone:12345678,recieverAddress:中国上海}
  $.ajax({
    url: '',
    type: 'post',
    data: {
      receiverInfo:recieverMsg,//收件人信息
    },
    traditional:true,
    success: function(data){
      console.log(data);

    },
    error: function() {
      alert("新增订单失败")
    }
  })
Copy after login

The above is the detailed content of How to obtain multiple pieces of data in a form field and convert them into json format. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template