如果要跳转页面,那么form上要定义action跳转到相关页面,同时提交按钮的type要为submit,如下:
<
form
action
=
"test2.php"
method
=
"post"
>
<input type="submit" value="提交" />
不跳转用ajax刷新的代码如下:
html代码:
<body>
<div align="center">
<form id="form1" name="form1" method="post" action="test2.php">
<table width="500" border="1" cellspacing="0" cellpadding="5">
<tr>
<td colspan="2" align="center" bgcolor="#CCCCCC"><strong>用户注册</strong></td>
</tr>
<tr>
<td width="101" align="right">用户名:</td>
<td width="393" align="left"><label>
<input type="text" name="username" />
</label></td>
</tr>
<tr>
<td align="right">密码:</td>
<td align="left"><label>
<input type="text" name="password" />
</label></td>
</tr>
<tr>
<td align="right"> </td>
<td align="left"><label>
<input type="submit" name="Submit" value="提交" />
<input type="reset" name="Submit2" value="重置" />
</label></td>
</tr>
</table>
</form>
</div>
<br /><br />
<div id="d1" style="font-size:35px; text-align:center;"> </div>
</body>
JS代码:
<script language="javascript">
function f1()
{
//创建xmlHttp对象
var xmlHttp;
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
//获取表单值
var username=document.form1.username.value;
var password=document.form1.password.value;
var datastr="username="+username+"&password="+password;
var url="/test2.php";
//提交数据
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
document.getElementById("d1").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(datastr);
}
</script>
PHP代码:
<?php
$conn = mysql_connect(‘localhost‘,‘root‘,‘‘);
mysql_query("set names utf-8");
mysql_select_db( "test" );
function inject_check($sql_str){
return preg_match("/select|insert|update|delete|\‘|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|%|eval|=|and|‘|;|exec|count/i", $sql_str); // 进行过滤
}
if(!empty($_POST)){
foreach($_POST as $key => $value){
if(inject_check($value)){
exit (‘<script>alert("地址栏输入发现有非法字符,请重新输入!");history.go(-1);</script>‘);
die ();
}
}
}
//这里的变量名改成相应的变量名
$res = mysql_query("SELECT count(*) as m from `user` where username=‘${_POST[‘username‘]}‘ AND password=‘${_POST[‘password‘]}‘");
$row = mysql_fetch_object($res);
if($row->m >0){
echo "登陆成功";
}else{
echo "登陆失败";
}
exit;
?>
原文地址:http://10145212.blog.51cto.com/10135212/1653919