//ajax的封装函数
function ajax(ops){
// 先处理默认属性
ops.type = ops.type || "get";
ops.data = ops.data || "";
// 根据当前的请求方式,决定是否需要拼接数据,处理url
ops.url = ops.type=="get" ? ops.url + "?" + ops.data : ops.url;
// if(ops.type=="get"){
// ops.url = ops.url+ops.data
// }
// 创建xhr对象
var xhr = new XMLHttpRequest();
// 开启请求
xhr.open(ops.type, ops.url);
// 根据类型决定send的内容及内容数据格式
if(ops.type == "get"){
xhr.send();
}else{
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(ops.data);
}
// 开启监听
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
// 执行回调函数,取出数据
ops.success(xhr.responseText);
}
}
}
简单实例
//当点击页面时,实现get-post.php内数据的显示
document.onclick = function(){
// 给定请求路径
var url = "http://localhost/ajax/data/get-post.php";
ajax({
success:function(res){
console.log(res);
},
url:url,
type:"get",
data:"user=admin&pass=123"
});
}
php代码:
<?php
// 既能接收get数据,又能接收post数据
$u = $_REQUEST["user"];
$p = $_REQUEST["pass"];
echo "后台接收到的数据:".$u."---".$p;
?>
效果图: