鍍金池/ 問答/Java  PHP  網(wǎng)絡(luò)安全/ 提交 json 格式給對方

提交 json 格式給對方

{
    "list": [
        {
            "attribute-id": "f11",
            "name": "love",
            "type": "me"
        },
        {
            "attribute-id": "f12",
            "name": "member",
            "type": "her"
        },
        {
            "attribute-id": "f13",
            "name": "user",
            "type": "her"
        },
        {
            "attribute-id": "f14",
            "name": "like",
            "type": "me"
        }
    ]
}

假設(shè)是多選項(xiàng)的checkbox
選項(xiàng)假設(shè)有20個
我要POST提交給對方是這樣的格式
那我這邊要怎麼寫才對???我想半天!
而以上這四個是我從20中選出來的結(jié)果!

回答
編輯回答
苦妄

html 代碼可能長得下面這樣:

<!-- 選項(xiàng)列表 -->
<div class='header'>選項(xiàng)</div>
<div class='cbox-list'>
<label>
    <input type='checkbox' class='cbox-input' data-id='f12' data-type='member' data-name='her' />her
</label>

<label>
    <input type='checkbox' class='cbox-input' data-id='f11' data-type='love' data-name='me' />me
</label>
</div>

JavaScript 代碼可能長得下面這種:

var cBoxInputSet = document.querySelectorAll('.cbox-list .cbox-input');
// 待提交的數(shù)據(jù)
var postData = {
    list: []
};
var cur = null;
var single = null;
for (var i = 0; i < cBoxInputSet.length; ++i)
{
    cur = cBoxInputSet[i];
    
    if (cur.checked) {
        single = {
            "attribute-id": cur.getAttribute('data-id') , 
            type: cur.getAttribute('data-type') , 
            name: cur.getAttribute('data-name')
        };
        
        postData['list'].push(single);
    }
}

// 這個就是要發(fā)送的數(shù)據(jù)了
postData = JSON.stringify(postData);

postData 格式如下:

{
    "list": [
        {
            "attribute-id": "f11" , 
            "name": "me" , 
            "type": "love"
        } , 
        ....
    ]
}
2018年2月25日 04:35
編輯回答
終相守

如下所示

const  selectList = {
    "list": [
        {
            "attribute-id": "f11",
            "name": "love",
            "type": "me"
        },
        {
            "attribute-id": "f12",
            "name": "member",
            "type": "her"
        },
        {
            "attribute-id": "f13",
            "name": "user",
            "type": "her"
        },
        {
            "attribute-id": "f14",
            "name": "like",
            "type": "me"
        }
    ]
}
$.ajax({
    url: 'xxx-url',
    type: "post",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    data:JSON.stringify(selectList),
});
2017年1月15日 16:17