在一个html页面中,需要提交表单给另一个页面,我们希望在后台运行,而不打开新页面,有两种方法:
1、iframe方法
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<script type="text/javascript">
</script>
</head>
<body>
<iframe name="testserver" style="display:none;" src=''></iframe>
<form name="settest" action="test.cgi" target="testserver">
<table>
<tr><td>
用户名:</td><td><input type="text" INPUT NAME="username" SIZE="30" maxlength="20"></td></tr>
<tr><td>
密码:</td><td><input type="text" INPUT NAME="password" SIZE="30" maxlength="20"></td></tr>
<tr><td>
<input type="submit" value="保存"></td></tr>
</table>
</Form>
</body>
</html>
test.cgi可以替换为任意要转向的html网页,form的target需要与iframe name保持一致
2、ajax方法
function createXHR()
{
ar xhr;
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xhr = new ActiveObject("Microsoft.XMLHTTP");
}
catch(E)
{
xhr = false;
}
}
if(!xhr && typeof XMLHttpRequest != 'undefined')
{
xhr = new XMLHttpRequest();
}
return xhr;
}
function sender(val)
{
xhr = createXHR();
if(xhr)
{
xhr.onreadystatechange = callbackFunction;
xhr.open("GET","test.cgi?"+val); //调用test.cgi程序,val为需要传递的参数
xhr.send(null);
}
else
{
alert("浏览器不支持,请更换浏览器!");
}
}
function callbackFunction()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
var returnValue = xhr.responseText;//returnValue为test.cgi返回的结果
}
else
{
alert("页面出现异常!");
}
}
}