Home >Web Front-end >JS Tutorial >Sample code for automatically obtaining form element values ​​through JS code in Ajax

Sample code for automatically obtaining form element values ​​through JS code in Ajax

亚连
亚连Original
2018-05-25 15:33:091461browse

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!=&#39;&#39; )
{
if ( item.type == &#39;select-one&#39; )
{
itemValue = item.options[item.selectedIndex].value;
}
else if ( item.type==&#39;checkbox&#39; || item.type==&#39;radio&#39;)
{
if ( item.checked == false )
{
continue; 
}
itemValue = item.value;
}
else if ( item.type == &#39;button&#39; || item.type == &#39;submit&#39; || item.type == &#39;reset&#39; || item.type == &#39;image&#39;)
{
continue;
}
else
{
itemValue = item.value;
}
itemValue = escape(itemValue);
queryString += and + item.name + &#39;=&#39; + 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn