[英]Generate JSON using jQuery
我有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>
當我在jQuery中使用$('#mark_date_form').serializeArray()
時,它將返回
[
{
"name": "title",
"value": "motherday"
},
{
"name": "date",
"value": "05/13"
},
{
"name": "title",
"value": "fatherday"
},
{
"name": "date",
"value": "06/18"
}
]
問題是我必須提出類似這樣的內容:
[
{
"title": "motherday",
"date": "05/13"
},
{
"title": "fatherday",
"date": "06/18"
}
]
jQuery應該是什么樣子?
非常感謝你!
我認為您正在尋找這個$("#mark_date_form").serialize()
;
更新:對不起@ daniel-cai是正確的。 使用$("#mark_date_form").serializeArray();
用於獲取JavaScript文字對象。
您可以使用此:
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);
輸出:
[Object { title="motherday", date="05/13"}, Object { title="fatherday", date="06/18"}]
根據需要獲取json文件的簡單方法是:
var o = {};
$("#mark_date_form").serializeArray().map(function(x){o[x.name] = x.value;});
console.log(o);
結果:
Object {title: "motherday", date: "05/13"}
演示: http : //jsfiddle.net/gon250/s3xerkgc/1/
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.