使用jquery动态创建每个输入值的JSON [英] Creating a JSON dynamically with each input value using jquery
问题描述
我遇到了一种情况,我想通过PHP读取JSON格式的某些数据,但是我遇到了一些问题,需要理解如何构造Javascript对象来动态创建JSON格式。
我的情况如下:
< input title = QAtype =textclass =email>
< input title =PRODtype =textclass =email>
< input title =DEVtype =textclass =email>
到目前为止,Javascript代码都经历了每个输入抓取数据,但我无法理解如何从这里开始处理。
var taskArray = {};
$(input [class = email])。each(function(){
var id = $(this).attr(title);
var email = $(this).val();
//如何创建JSON?
});
如果可能,我想获得以下输出。
[{title:QA,email:'a@a.com'},{title:PROD,email:'b@b.com'},{title: DEV,email:'c@c.com'}]
通过输入获取电子邮件字段值。
这种情况下的任何灯光都将不胜感激!
函数createJSON(){
jsonObj = [];
$(input [class = email])。each(function(){
var id = $(this).attr(title);
var email = $(this).val();
item = {}
item [title] = id;
item [email] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
解释
您正在寻找一组对象
。所以,你创建一个空白数组。使用'title'和'email'作为键为每个 input
创建一个对象。然后你添加每个对象到数组中。
如果你需要一个字符串,那么做
jsonString = JSON.stringify(jsonObj);
输出样本
[{ 标题: QA, 电子邮件: 一个@ b},{ 标题: PROD, 电子邮件:b @ç },{title:DEV,email:c @ d}]
I got a situation where I would like to read some data off a JSON format through PHP, however I am having some issues understanding how I should construct the Javascript object to create the JSON format dynamically.
My scenario is as follows:
<input title="QA" type="text" class="email">
<input title="PROD" type="text" class="email">
<input title="DEV" type="text" class="email">
The Javascript code I have so far goes through each input grabs the data, I am however unable to understand how to process from here on.
var taskArray = {};
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
//how to create JSON?
});
I would like to get the following output if possible.
[{title: QA, email: 'a@a.com'}, {title: PROD, email: 'b@b.com'},{title: DEV, email: 'c@c.com'}]
Where the email is acquired by the input field value.
Any light shed on this situation will be greatly appreciated!
Like this:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item ["title"] = id;
item ["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
Explanation
You are looking for an array of objects
. So, you create a blank array. Create an object for each input
by using 'title' and 'email' as keys. Then you add each of the objects to the array.
If you need a string, then do
jsonString = JSON.stringify(jsonObj);
Sample Output
[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}]
这篇关于使用jquery动态创建每个输入值的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!