ajax以get和post方式请求
2017-08-19 17:04
429 查看
两者的不同
① 给服务器传递数据量,get最多是2kpost原则没有限制,php.ini对其限制为8M
② 安全方面,post传递数据较安全
③ 传递数据的形式不一样
get方式在url地址后边以请求字符串形式传递参数
http://网址/index.php?name=tom&age=23&addr=beijing
蓝色部分就是请求字符串,就是一些“名-值”对,中间使用&符号连接。
post方式是把form表单的数据给请求出来以xml形式传递给服务器
1、ajax之get方式请求
①在url地址后边以请求字符串(传递的get参数信息)形式传递数据。
② 对中文、=、&等特殊符号处理
=、&符号在浏览器里边会与请求字符串的关键符号有混淆,避免歧义产生需要对其进行编码.
在浏览器的地址栏里边传递一些特殊符号信息,会被误解,例如 & = 空格 中文。
在php里边可以函数函数
urlencode()/urldecode()对特殊符号进行编码、反编码处理
(url_encode()可以把中文转变为浏览器可以识别的信息。转变之后的信息具体为%号后接两个十六进制数)
在javascript里边可以通过encodeURIComponent ()对特殊符号等信息进行编码。
经过以上红色函数编码的内容在服务器端可以正常接收,不需要反编码。
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> function checkname() { //ajax负责抓取用户名信息,传递给服务器进行校验 //获得用户名信息 var username = document.getElementById('username').value; username = encodeURIComponent(username); //进行反编码,防止特殊字符 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if(xhr.readyState == 4){ alert(xhr.responseText); } } xhr.open('get', './04.php?name=' + username); xhr.send(null); } </script> </head> <body> <h2>get方式请求</h2> <form method="post" action=""> <p>用户名:<input type="text" name="username" id="username" onblur="checkname()"></p> <p>密码:<input type="password" name="userpwd"></p> <input type="submit" value="注册"> </form> </body> </html>效果图:
2、ajax之post方式请求
① 给服务器传递数据需要调用send(请求字符串数据)方法
② 调用方法setRequestHeader()把传递的数据组织为xml格式(模仿form表单给服务器传递数据)
③ 传递的中文信息无需编码,特殊符号像 &、=等 需要编码
④ 该方式请求的同时也可以传递get参数信息,同样使用$_GET接收该信息
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
function checkname() {
//ajax负责抓取用户名信息,传递给服务器进行校验
//获得用户名信息
var username = document.getElementById('username').value;
username = encodeURIComponent(username); //进行反编码,防止特殊字符
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
alert(xhr.responseText);
}
}
xhr.open('post', './05.php');
//把传递的数据组织为请求字符串,post模仿form表单传递给服务器(xml格式)
//下面设置以xml格式传递
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
var info = "name=" + username + '&age=20';
xhr.send(info);
}
</script>
</head>
<body>
<h2>post方式请求</h2>
<form method="post" action="">
<p>用户名:<input type="text" name="username" id="username" onblur="checkname()"></p>
<p>密码:<input type="password" name="userpwd"></p>
<input type="submit" value="注册">
</form>
</body>
</html>效果图:
相关文章推荐
- Ajax中的get和post两种请求方式的异同
- Ajax中的get和post两种请求方式的异同
- Ajax-(get/post/jQuery方式请求)
- Ajax以post方式传送带参的数据方式与get请求的不同
- $.ajax()post方式请求参数无法传递,request.getParameter()无法获取
- Ajax中的get和post两种请求方式的异同
- Ajax的请求方式GET/POST区别
- Ajax中的get和post两种请求方式的异同
- AJAX学习笔记之 客户端请求方式 get 和post 模式
- Ajax中的get和post两种请求方式的异同
- Ajax中get和post两种请求方式的用法
- Ajax的GET与POST方式向服务器发送请求
- 转:Ajax中的get和post两种请求方式的异同
- Ajax中的get和post两种请求方式的异同
- Ajax的请求方式:get和post
- javascript/js的ajax请求方式:GET与POST
- Ajax中的get和post两种请求方式的异同
- ajax中Post和Get请求方式的区别?
- Extjs6 设置Store、Ajax、form的请求方式(GET、POST)
- Ajax中请求方式(GET/POST)之GET方式