您的位置:首页 > Web前端 > JavaScript

纯js的ajax实现异步提交表单

2013-03-30 00:00 507 查看
很多时候需要异步提交表单,当表单太多是时候,一个个getElementById变得很不实际

当然,jquery可以实现异步提交表单,jquery.form.js这个库貌似也挺流行

只是有时候并不想使用额外的库,所以就琢磨着自己写,用纯js来实现异步提交表单

实现如下(本例用POST方式提交,用php作为服务器脚本):

form.html:

<html>
<head>
<script type="text/javascript" src="ajax_form.js"></script>
</head>
<body>
<form action="process.php" id="ajax_form">
Username:<input type="text" name="username"/><br>
Password:<input type="password" name="password"/><br>
Gender:<input type="radio" name="gender" value="male"/>Male 
<input type="radio" name="gender" value="female"/>Female<br>
Interest:<input type="checkbox" name="interest[]" value="programing"/>Programing 
<input type="checkbox" name="interest[]" value="game"/>Game 
<input type="checkbox" name="interest[]" value="sport"/>Sport
<input type="button" onclick="submitForm('ajax_form', 'tip')" value="Submit">
</form>
<div id="tip"></div>
</body>
</html>


ajax_form.js:

function createXmlHttp() {
var xmlHttp = null;

try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
//IE
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}

return xmlHttp;
}

function submitForm(formId, tipId) {
var xmlHttp = createXmlHttp();
if(!xmlHttp) {
alert("您的浏览器不支持AJAX!");
return 0;
}

var e = document.getElementById(formId);
var tip = document.getElementById(tipId);
var url = e.action;
var inputs = e.elements;
var postData = "";
for(var i=0; i<inputs.length; i++) {
switch(inputs[i].type) {
case "text":
postData += inputs[i].name + "=" + inputs[i].value + "&";
break;
case "password":
postData += inputs[i].name + "=" + inputs[i].value + "&";
break;
case "radio":
if(inputs[i].checked) {
postData += inputs[i].name + "=" + inputs[i].value + "&";
}
break;
case "checkbox":
if(inputs[i].checked) {
postData += inputs[i].name + "=" + inputs[i].value + "&";
}
break;
default:
continue;
}
}

postData += "t=" + Math.random();

xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
tip.innerHTML = xmlHttp.responseText;
}
}
xmlHttp.send(postData);
}


process.php:

<?php
$text = "The data that you submit:";
$text .= "<br>Username: " . $_POST['username'];
$text .= "<br>Password: " . $_POST['password'];
$text .= "<br>Gender: " . $_POST['gender'];
$text .= "<br>Interest:";
for($i=0; $i<count($_POST["interest"]); $i++) {
$text .= " " . $_POST["interest"][$i];
}
echo $text;
?>


测试如下:

提交前:



提交后:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息