If there are not many form elements, we often use GET to get the form element value. But if there are many form elements, we need to use POST to get the form element value. So how to get the form element value?
When we use Ajax, we usually need to obtain the form element value and then send it to the background server-side program for processing. If there are not many form elements, we often get the form element values through GET. But if there are many form elements, we need to use POST to get the form element values. So how to get the form element values? The following is a piece of JS code that can automatically obtain the value of the form element.
function getFormQueryString(frmID) //frmID是表单的ID号,请在表单form中先命名一个ID号 { var frmID=document.getElementById(frmID); var i,queryString = "", and = ""; var item; var itemValue; for( i=0;i<frmID.length;i++ ) { item = frmID[i]; if ( item.name!='' ) { if ( item.type == 'select-one' ) { itemValue = item.options[item.selectedIndex].value; } else if ( item.type=='checkbox' || item.type=='radio') { if ( item.checked == false ) { continue; } itemValue = item.value; } else if ( item.type == 'button' || item.type == 'submit' || item.type == 'reset' || item.type == 'image') { continue; } else { itemValue = item.value; } itemValue = escape(itemValue); queryString += and + item.name + '=' + itemValue; and="&"; } } return queryString; }
Calling method: Call the above JS function directly in Ajax to get the values of all elements in the form.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
AJAX Elementary Tutorial: Getting to Know AJAX
AJAX Encapsulation Class Usage Guide
Detailed explanation of browser and server interaction in Ajax
The above is the detailed content of Sample code for automatically obtaining form element values through JS code in Ajax. For more information, please follow other related articles on the PHP Chinese website!