原生js实现获取form表单数据

//获取指定form中的所有的对象  
function getElements(formId) {  
    var form = document.getElementById(formId);  
    var elements = new Array();  
    var tagElements = form.getElementsByTagName('input');  
    for (var j = 0; j < tagElements.length; j++){ 
       elements.push(tagElements[j]); 
    } 
    var tagElements = form.getElementsByTagName('select');  
    for (var j = 0; j < tagElements.length; j++){ 
       elements.push(tagElements[j]); 
    } 
    var tagElements = form.getElementsByTagName('textarea');  
    for (var j = 0; j < tagElements.length; j++){ 
        elements.push(tagElements[j]); 
    }
    return elements;  
}  
//组合URL 
function serializeElement(element) {  
    var method = element.tagName.toLowerCase();  
    var parameter;  
    if(method == 'select'){
        parameter = [element.name, element.value]; 
    }
    switch (element.type.toLowerCase()) {  
        case 'submit':  
        case 'hidden':  
        case 'password':  
        case 'text':
        case 'date':
        case 'textarea':  
             parameter = [element.name, element.value];
             break;
        case 'checkbox':  
        case 'radio':  
            if (element.checked){
                parameter = [element.name, element.value];  
            }
            break;       
    }  
    if (parameter) {  
       var key = encodeURIComponent(parameter[0]);  
       if (key.length == 0) 
            return;  
       if (parameter[1].constructor != Array)  
            parameter[1] = [parameter[1]];  
       var values = parameter[1];  
       var results = [];  
       for (var i = 0; i < values.length; i++) {  
            results.push(key + '=' + encodeURIComponent(values[i]));  
       }  
       return results.join('&');  
    }  
}  
//调用方法   
function serializeForm(formId) {  
    var elements = getElements(formId);  
    var queryComponents = new Array();  
    for (var i = 0; i < elements.length; i++) {  
        var queryComponent = serializeElement(elements[i]);  
        if (queryComponent) {
            queryComponents.push(queryComponent);  
        } 
    }  
    return queryComponents.join('&'); 
} 

最后通过serializeForm(formId);输入form的id名称即可实现,返回数据为

id=1&title=%E6%B4%BB%E5%8A%A8&time=2017-07-10&status=1&importance=0&desc=%E5%9C%A8%E4%BA%8C%E6%A5%BC%E5%8A%9E%E5%85%AC%E5%AE%A4%E5%BC%80%E4%BC%9A%EF%BC%8C%E4%B8%80%E7%82%B9%E9%92%9F

已经将数据编码

你可能感兴趣的:(javascript)