javascript 將form輸入的資料轉成json

function getFormDataAsJson(sFormId) {

    var form = $('#' + sFormId);
    if (form != null) {
        var json = {};

        var inputs = $('input', form);

        for (i = 0; i < inputs.length; ++i) {
            var next = inputs[i];
            var key = $(next).attr('id');
            var val = $(next).val();

            if (val != null && key != null)
                json[key] = val;
        }

        var selects = $('select', form);

        for (i = 0; i < selects.length; ++i) {
            var next = selects[i];
            var key = $(next).attr('id');
            var val = $(next).val();

            if (val != null && key != null)
                json[key] = val;
        }
        console.log(json);
        return json;
    }
}

發表迴響