function ajaxSubmitForm(form, resultDivId) {
var elements = form.elements;// Enumeration the form elements
var element;
var i;
var postContent = "";// Form contents need to submit
for(i=0;i<elements.length;++i) {
var element=elements[i];
if(element.type=="text" || element.type=="textarea" || element.type=="hidden") {
postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
}
else if(element.type=="select-one"||element.type=="select-multiple") {
var options=element.options,j,item;
for(j=0;j<options.length;++j){
item=options[j];
if(item.selected) {
postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(item.value) + "&";
}
}
} else if(element.type=="checkbox"||element.type=="radio") {
if(element.checked) {
postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
}
} else if(element.type=="file") {
if(element.value != "") {
postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
}
} else {
postContent += encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value) + "&";
}
}
alert(postContent);
ajaxSubmit(form.action, form.method, postContent);
}
// url - the url to do submit
// method - "get" or "post"
// postContent - the string with values to be submited
// resultDivId - the division of which to display result text in, in null, then
// create an element and add it to the end of the body
function ajaxSubmit(url, method, postContent, resultDivId) {
var loadingDiv = document.getElementById('loading');
// call in new thread to allow ui to update
window.setTimeout(function () {
loadingDiv.innerText = "Loading....";
loadingDiv.style.display = "";
}, 1);
// code for Mozilla, etc.
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// code for IE
else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp) {
xmlhttp.onreadystatechange = function() {
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4) {
if(resultDivId) {
document.getElementByID(resultDivId).innerHTML = xmlhttp.responseText;
} else {
var result = document.createElement("DIV");
result.style.border="1px solid #363636";
result.innerHTML = xmlhttp.responseText;
document.body.appendChild(result);
}
loadingDiv.innerHTML = "Submit finnished!";
}
};
if(method.toLowerCase() == "get") {
xmlhttp.open("GET", url + "?" + postContent, true);
xmlhttp.send(null);
} else if(method.toLowerCase() == "post") {
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(postContent);
}
} else {
loadingDiv.innerHTML = "Can't create XMLHttpRequest object, please check your web browser.";
}
}
ajax提交表单
最新推荐文章于 2022-04-08 16:19:26 发布