表单提交的两种方式区别

表单提交的两种方式区别

1 submit提交表单会刷新页面,页面将跳转到你提交的那个页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1 style="color:red">submit提交表单会刷新页面,页面将跳转到你提交的那个页面</h1>
<form action="22.php" method="post">
姓名:<input type="text" name = "name">
密码:<input type="password" name = "password">
<input type="submit" value="提交">
</form>
</body>
</html>

-------------------分割线----------------------------------

2 ajax提交只是页面的局部刷新不会跳转到你提交的那个页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1 style="color:red">ajax提交只是页面的局部刷新不会跳转到你提交的那个页面</h1>
<form id = "formdata">
姓名:<input type="text" name = "name" id = "name">
密码:<input type="password" name = "password" id = "password">
<input type="button" value="提交" id="btn">
</form>
<script src="jquery.min.js"></script>
<script>
$(function(){
$("#btn").click(function(){
// 一次性获得表单数据
var formData = $("#formdata").serialize();

$.ajax({
url: '22.php',
type: 'post',
data: formData,
// 提交之前校验数据
beforeSend:function(){
if($('#name').val() == ''){
alert("用户名不能为空");
return false;
}
},
success:function(data){
// 查看php返回来的数据格式
console.log(typeof data);
// 将字符串转成对象我们想要的格式
data = JSON.parse(data);
console.log(data);
if(data.code == 1){
alert(data.msg);
// 登录成功后跳转到另一个页面
location.href = "08ajaxtempletechat.html";
}else{
alert(data.msg);
}
}
})


});
})
</script>
</body>
</html>

--------------------php-------------------

php

<?php
header('Content-type:text/html;charset = utf-8');
//接受用户传来的数据
$name = $_POST['name'];
$pass = $_POST['password'];
//模拟从数据库查询的用户名数据
$users = array(
'admin' => 123,
'xiaoli' => 456
);

//检测用户输入进来的用户名在数据库中是否存在
$hasname = array_key_exists($name, $users);
//用户输入的名字在数据库中存在并且数据库中已有的密码跟用户输进去的一致
if($hasname && $users[$name] == $pass){
$result = array(
'code' => 1,
'msg' => "登录成功"
);
echo json_encode($result);
}else{
$result = array(
'code' => 0,
'msg' => "登录失败"
);
echo json_encode($result);
}
?>

原文地址:https://www.cnblogs.com/niuniuniu/p/6417923.html