Home  >  Article  >  Web Front-end  >  JS obtains multiple pieces of data in a form field and converts them into json format. Example sharing

JS obtains multiple pieces of data in a form field and converts them into json format. Example sharing

小云云
小云云Original
2018-01-15 10:32:432093browse

This article mainly introduces the relevant information about JS obtaining multiple data in a form field and converting it into json format. Friends who need it can refer to it. I hope it can help everyone.

As shown in the figure, we need to obtain the data in the following two li tags and then pass them to the backend; and the data format received by the backend is json, so we need to get the data in the two li tags The information is converted into the following format.


{recieverName:小红,recieverPhone:12341234,recieverAddress:中国湖南},{recieverName:小明,recieverPhone:12345678,recieverAddress:中国上海}

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("新增订单失败")
  }
 })

Related recommendations:

Ajax submission sample code in json format

Detailed explanation of json format control in php

java converts XML documents into json format data

The above is the detailed content of JS obtains multiple pieces of data in a form field and converts them into json format. Example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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