Bac*_*ice 78 html javascript jquery html5 json
我有一种情况,我想通过PHP读取JSON格式的一些数据,但是我有一些问题需要理解我应该如何构造Javascript对象来动态创建JSON格式.
我的方案如下:
<input title="QA" type="text" class="email">
<input title="PROD" type="text" class="email">
<input title="DEV" type="text" class="email">
Run Code Online (Sandbox Code Playgroud)
到目前为止我的Javascript代码经过每个输入抓取数据,但是我无法从这里了解如何处理.
var taskArray = {};
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
//how to create JSON?
});
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想获得以下输出.
[{title: QA, email: 'a@a.com'}, {title: PROD, email: 'b@b.com'},{title: DEV, email: 'c@c.com'}]
Run Code Online (Sandbox Code Playgroud)
通过输入字段值获取电子邮件的位置.
任何有关这种情况的灯光都将不胜感激!
ATO*_*TOA 237
像这样:
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);
}
Run Code Online (Sandbox Code Playgroud)
说明
你在找an array of objects.因此,您创建一个空白数组.input使用'title'和'email'作为键为每个对象创建一个对象.然后将每个对象添加到数组中.
如果你需要一个字符串,那么就做
jsonString = JSON.stringify(jsonObj);
Run Code Online (Sandbox Code Playgroud)
样本输出
[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}]
Run Code Online (Sandbox Code Playgroud)
Chr*_*isF 13
假设您需要JSON字符串作为输出,我认为您不能仅使用jQuery将JavaScript对象转换为JSON字符串.
根据您定位的浏览器,您可以使用该JSON.stringify函数生成JSON字符串.
有关更多信息,请参阅http://www.json.org/js.html,在那里您还可以找到本机不支持JSON对象的旧浏览器的JSON解析器.
在你的情况下:
var array = [];
$("input[class=email]").each(function() {
array.push({
title: $(this).attr("title"),
email: $(this).val()
});
});
// then to get the JSON string
var jsonString = JSON.stringify(array);
Run Code Online (Sandbox Code Playgroud)
可能这会有所帮助,我更喜欢纯JS,它会大大提高性能,因为你不会有很多JQuery函数调用.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
Run Code Online (Sandbox Code Playgroud)