Get请求
数据量有限制,隐私暴露在地址栏,不安全。
栗子:
HTML代码:
用户名称:<input type="text" name="" value="" id="txtName">
<span id="txtNameTip">**</span>
JavaScript代码:
//获得XMLHttpRequest对象,分IE5.5--IE6 和 IE7以上Chrome、FF...两大类
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}
$(function(){
$("#txtName").blur(function(){
//获取xhr
var xhr = getXhr();
//创建请求
var name = $("#txtName").val();
var url = "checkName.php?name=" + name;
xhr.open("get",url,true);
//状态变化
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
$("#txtNameTip").html(xhr.responseText);
}
}
//发送请求
xhr.send(null);
});
PHP代码:
<?php
//用接受的数据与admin进行判断
//接收用户提交的数据
$name = $_REQUEST["name"];
if($name=="admin"){
echo "用户名已存在";
}else{
echo "通过";
}
?>
页面:
注意点:
使用get请求,xhr.send(null) 中一定要定参数null。
需要传的参数在url中拼接。
post请求
数据量没有限制,隐私不会暴露在地址栏,安全。
栗子:
HTML代码:
用户名称:<input type="text" name="" value="" id="txtName">
<span id="txtNameTip">**</span>
JavaScript代码:
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}
$(function(){
$("#txtName").blur(function(){
//获取xhr
var xhr = getXhr();
//创建请求
var name = $("#txtName").val();
var url = "checkName.php"; //与get请求不一样的地方
xhr.open("post",url,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //与get请求不一样的地方
//状态变化
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
$("#txtNameTip").html(xhr.responseText);
}
}
//发送请求
xhr.send("name=" + name); //与get请求不一样的地方
});
PHP代码与get请求相同。
结果也与get请求相同。
注意:
使用post请求,参数写在xhr.send()方法内,多个参数用 “&” 符号相连接。
使用post请求,一定记住要手动设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
代码在创建请求和发送请求之间均可。
AJAX请求大致的四步:
- 得到XMLHttpRequest对象。
- 创建请求。xhr.open(method,url,aysn);
- 设置回调函数:指定xhr.onreadystatechange事件
- 发送请求。xhr.send();