简体   繁体   English

使用jQuery生成JSON

[英]Generate JSON using jQuery

I have 4 inputs in a form: 我有4种输入形式:

<form id="mark_date_form">
   <input type="text" name="title" class="form-control" placeholder="Title" value="motherday">
   <input type="text" name="date" class="form-control datepick" placeholder="MM/DD" value="05/13">

   <input type="text" name="title" class="form-control" placeholder="Title" value="fatherday">
   <input type="text" name="date" class="form-control datepick " placeholder="MM/DD" value="06/18">
</form>

When I use $('#mark_date_form').serializeArray() in jQuery, it returns 当我在jQuery中使用$('#mark_date_form').serializeArray()时,它将返回

[
    {
        "name": "title",
        "value": "motherday"
    },
    {
        "name": "date",
        "value": "05/13"
    },
    {
        "name": "title",
        "value": "fatherday"
    },
    {
        "name": "date",
        "value": "06/18"
    }
]

The question is I have to come out with something like this: 问题是我必须提出类似这样的内容:

[
    {
        "title": "motherday",
        "date": "05/13"
    },
    {
        "title": "fatherday",
        "date": "06/18"
    }
]

What should be the jQuery looks like? jQuery应该是什么样子?

Thank you very much! 非常感谢你!

I think you are looking for this $("#mark_date_form").serialize() ; 我认为您正在寻找这个$("#mark_date_form").serialize() ;

Update: sorry for the @daniel-cai is correct. 更新:对不起@ daniel-cai是正确的。 Use $("#mark_date_form").serializeArray(); 使用$("#mark_date_form").serializeArray(); for getting JavaScript literal object. 用于获取JavaScript文字对象。

You can use this: 您可以使用此:

var a = [];
$('#mark_date_form input').each(function(){
    if($(this).attr('name')=='title'){
        a.push({"title":$(this).val(),"date":$(this).next().val()});
    }
});
console.log(a);

Output: 输出:

[Object { title="motherday",  date="05/13"}, Object { title="fatherday",  date="06/18"}]

Simple way to get a json file as you want is: 根据需要获取json文件的简单方法是:

var o = {};
$("#mark_date_form").serializeArray().map(function(x){o[x.name] = x.value;}); 
console.log(o);

Result: 结果:

Object {title: "motherday", date: "05/13"}

DEMO: http://jsfiddle.net/gon250/s3xerkgc/1/ 演示: http : //jsfiddle.net/gon250/s3xerkgc/1/

Hope it's helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM