Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - 使用jquery使用每个输入值动态创建JSON(Creating a JSON dynamically with each input value using jquery)

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.(我有一种情况,我想通过PHP读取JSON格式的一些数据,但是我有一些问题需要理解我应该如何构造Javascript对象来动态创建JSON格式。)

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.(到目前为止我的Javascript代码经过每个输入抓取数据,但是我无法从这里了解如何处理。)

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: '[email protected]'}, {title: PROD, email: '[email protected]'},{title: DEV, email: '[email protected]'}]

Where the email is acquired by the input field value.(通过输入字段值获取电子邮件的位置。)

Any light shed on this situation will be greatly appreciated!(任何有关这种情况的灯光都将不胜感激!)

  ask by BaconJuice translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 .(您正在寻找an array of objects 。)

So, you create a blank array.(因此,您创建一个空白数组。) Create an object for each input by using 'title' and 'email' as keys.(使用'title'和'email'作为键为每个input创建一个对象。) 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"}] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...