setForm
setForm是一個很好用的function,所以把他從YAHOO.util.Connect給抽出來了,他的作用就是:給他一個form的id,他會把form裡面所有的form element的key value給組合成request str。
demo:http://chunghe.googlecode.com/svn/trunk/experiment/setForm.htm
function setForm(formId){
var oForm;
if(typeof formId == 'string'){
// Determine if the argument is a form id or a form name.
// Note form name usage is deprecated, but supported
// here for backward compatibility.
oForm = (document.getElementById(formId) || document.forms[formId]);
}
else if(typeof formId == 'object'){
// Treat argument as an HTML form object.
oForm = formId;
}
else{
return;
}
var hasSubmit = false;
var sFormData = '';
for (var i=0; i<oForm.elements.length; i++){
oElement = oForm.elements[i];
oDisabled = oElement.disabled;
oName = oElement.name;
oValue = oElement.value;
// Do not submit fields that are disabled or
// do not have a name attribute value.
if(!oDisabled && oName)
{
switch(oElement.type)
{
case 'select-one':
case 'select-multiple':
for(var j=0; j<oElement.options.length; j++){
if(oElement.options[j].selected){
if(window.ActiveXObject){
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].attributes['value'].specified?oElement.options[j].value:oElement.options[j].text) + '&';
}
else{
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].hasAttribute('value')?oElement.options[j].value:oElement.options[j].text) + '&';
}
}
}
break;
case 'radio':
case 'checkbox':
if(oElement.checked){
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
}
break;
case 'file':
// stub case as XMLHttpRequest will only send the file path as a string.
case undefined:
// stub case for fieldset element which returns undefined.
case 'reset':
// stub case for input type reset button.
case 'button':
// stub case for input type button elements.
break;
case 'submit':
if(hasSubmit === false){
if(this._hasSubmitListener && this._submitElementValue){
sFormData += this._submitElementValue + '&';
}
else{
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
}
hasSubmit = true;
}
break;
default:
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
}
}
}
sFormData = sFormData.substr(0, sFormData.length - 1);
return sFormData;
}
沒有留言:
張貼留言