基本概念
- XMLHttpRequest 是 AJAX 的基础。
- 定义传输类型 get,post
- 定义后台访问url(例:xhr.php)
- 定义open()方法
- 定义请求状态 onreadystatechange事件,
http.readyState存在四种状态:
— 0:初始化。没执行open()方法
— 1:启动,调用open()方法
— 2:发送,已经调用send()方法,但尚未—– 接收到响应
— 3:接收。已经接收到部分响应数据
— 4完成。已经接收到全部响应数据。http.send() 发送请求
分别定义了两个方法用来调用get和post方法
<!doctype html>
<html>
<meta charset="utf-8">
<title>ajax的两种值方式,post/get</title>
<head>
<style type="text/css">
</style>
</head>
<body>
姓名:<input type="text" value="" id="name">
<br>
<br>
密码:<input type="text" value="" id="password">
<br>
<br>
<input type="button" onclick="login()" value="get登录">
<input type="button" onclick="comfin()" value="post登录">
<script type="text/javascript" >
///用get登录
function login(){
var http = null;
function createHTTP() {
if (window.ActiveXObject) {
//此浏览器对象为ie浏览器
http = new window.ActiveXObject('Microsoft.XMLHTTP');
} else {
//否则为其他浏览器
http = new XMLHttpRequest();
}
return http;
}
var name=document.getElementById("name").value;
var password=document.getElementById("password").value;
var http=new XMLHttpRequest();
var url="http://localhost:8090/h5edu/09.02/index.php?name="+name+"&password="+password;
http.open('GET',url,true);
http.onreadystatechange=function(){
if (http.readyState == 4) {
if (http.status == 200) {
alert(http.responseText);
}
}
};
http.send();
}
///用post登录
function comfin(){
var http = null;
var name=document.getElementById("name").value;
var password=document.getElementById("password").value;
function createHTTP() {
if (window.ActiveXObject) {
//此浏览器对象为ie浏览器
http = new window.ActiveXObject('Microsoft.XMLHTTP');
} else {
//否则为其他浏览器
http = new XMLHttpRequest();
}
return http;
}
var content="name="+name+"&password="+password;
var http=new XMLHttpRequest();
var url="http://localhost:8090/h5edu/09.02/index2.php";
http.open('POST',url,true);
http.onreadystatechange=function(){
if (http.readyState == 4) {
if (http.status == 200) {
alert(http.responseText);//用于返回请求
}
}
};
http.setRequestHeader("CONTENT-TYPE", "application/x-www-form-urlencoded"); //模仿form表单提交登录
http.send(content);
}
</script>
</body>
</html>
php后台get,index.php
<?php
header("Content-Type:text/html;charset=utf-8");
$name=$_GET['name'];
$password=$_GET['password'];
echo '我的用户名是:';
echo $name;
echo "我的密码是:";
echo $password;
?>