一 原生JS中ajax请求
1.创建异步对象
var xmlHttp = new XMLHttpRequest()
2.设置请求
//第一个参数为请求方式('GET'/'POST'),第二个URL,第三个一般为true(异步),false(同步)
xmlHttp.open('POST',URL,true);
3.设置请求头
//(1)get方式不用设置
//(2)post方法需要设置请求头
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
4.设置请求体
//(1)get方式不需要设置参数(get中的传递的参数在URL中已经拼接,所以不需要)
xmlHttp.send(null);
//(2)post方式需要设置参数()例:xmlHttp.send('userName=' + unValue.value + "&userPassword=" + updValue.value)
xmlHttp.send(userBean);
5.让异步对象接受服务器响应数据
xmlHttp.onreadystatechange = function() {
//响应成功有两个条件需满足(1)服务器成功响应(2)异步对象的响应状态为4
if(this.status == 200 && this.readyState == 4){
console.log(this.responseText);
}
};
实例
html文件代码
<!DOCTYPE html>
<html lang="zh">
<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></title>
</head>
<body>
</body>
<form >
<label for="">账户:</label>
<input type="text" name="userName" id="un" value=""/><br>
<label for="">密码:</label>
<input type="password" name="userPassword" id="upd" value=""/><br>
<input type="button" value="提交" id="btn"/>
</form>
<script type="text/javascript">
var btn = document.querySelector('#btn');
var unValue = document.querySelector('#un');
var updValue = document.querySelector('#upd');
btn.addEventListener('click',function() {
var userBean = 'userName=' + unValue.value + "&userPassword=" + updValue.value;
console.log(userBean);
//1.创建异步对象
var xmlHttp = new XMLHttpRequest()
//2.设置请求行open()
xmlHttp.open('POST','DOM9(yspost).php',true);
//3.设置请求
//(1)get方式不用设置
//(2)post方法需要设置请求头
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4.设置请求体
//(1)get方式不需要设置参数(get中的传递的参数在URL中已经拼接,所以不需要)
//(2)post方式需要设置参数()例:xmlHttp.send('userName=' + unValue.value + "&userPassword=" + updValue.value)
xmlHttp.send(userBean);
//5.让异步对象接受服务器响应数据
xmlHttp.onreadystatechange = function() {
//响应成功有两个条件需满足(1)服务器成功响应(2)异步对象的响应状态为4
if(this.status == 200 && this.readyState == 4){
console.log(this.responseText);
var resp = JSON.parse(this.responseText);
if(resp.flag == 0){
alert('失败');
}else{
alert(resp.success);
}
}
};
});
</script>
</html>
PHP文件代码
<?php
$userName =$_POST['userName'];
$userPwd =$_POST['userPassword'];
$mess = array('success'=>'成功');
$message = JSON_encode($mess);
if($userName == 'xx' && $userPwd == '111') {
echo $message;
}else{
echo '{"flag":0}';
}
?>
二 jQuery中ajax请求
$.ajax({
type:"get",// get或者post
url:"abc.php",// 请求的url地址
data:{},//请求的参数
dataType:"json",//json写了jq会帮我们转换成数组或者对象 他已经用JSON.parse弄好了
timeout:3000,//3秒后提示错误
beforeSend:function(){
// 发送之前就会进入这个函数
// return false 这个ajax就停止了不会发 如果没有return false 就会继续
},
success:function(data){ // 成功拿到结果放到这个函数 data就是拿到的结果
},
error:function(){//失败的函数
},
complete:function(){//不管成功还是失败