get和post的区别
说明:无论是用ajax还是form表单来实现交互,首先我们要明确get和post的使用场合
get是限制长度的,post不会
get请求数据大小不超过2000字符左右,post无限制
get请求的查询字符串显示在地址栏,post不会,即是post更安全
本文实现功能
通过ajax的get或post方法,发送一个查询字符串uname=lisi&upwd=123456请求,并响应回来结果,信息正确与否;
common.js文件
common.js文件,简化一些dom操作和复杂固定步骤
function $(id) {
return document.getElementById(id);
} //简化document.getElementById()这个api
function createXhr(){//简化创建异步对象
var xhr=null;
if(window.XMLHttpRequest==null){
xhr=new ActiveXObject(“Microsoft.XMLHttp”);
}else{
xhr=new XMLHttpRequest();
}
return xhr;
}
ajax.php
用于接收网页传过来的请求数据,并返回结果
<?php $uname=$_REQUEST["uname"]; $upwd=$_REQUEST["upwd"]; if($uname=="lisi"&&$upwd==123456){ echo "登录成功"; }else{ echo "登录失败"; } ?>ajax-post.html
用post提交数据,post方法注意两点:1是要设置请求主体,2是把拼接的查询字符串放到xhr.send()里面
ajax-get.html
用get提交,注意:1拼接好的URL写在xhr.open() 2xhr.send()里面为null
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>用户名称:<input type="text" id="uname"></p>
<p>用户密码:<input type="password" id="upwd"></p>
<input type="button" value="提交" onclick="sendMsg()">
<script src="common.js"></script>
<script>
function sendMsg(){
var xhr=createXhr();//设置异步对象
//拼接URL
var uname=$("uname").value;
var upwd=$("upwd").value;
var url="ajax.php?uname="+uname+"&upwd="+upwd;
xhr.open("post",url,true);//设置异步请求
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
var res=xhr.responseText;//接受响应结果
alert(res);
}
}
xhr.send(null);//设置为null
}
</script>
</body>
</html>
init.php
该文件是一个通用的,用于简化ajax.php文件,这里这个文件并没有过多的作用,用到数据库时作用大
<?php
$conn=mysqli_connect("127.0.0.1","root","","xz",3306);//连接数据库
$sql="SET NAMES UTF8";//设置编码格式
mysqli_query($conn,$sql);
?>
结果显示
通过地址栏去访问上述.html文件,如果得到以下结果,恭喜你学会了