Ajax的GET形式进行数据交互
前端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax的GET简易使用</title>
</head>
<body>
<button onclick="ajax()">获取信息</button>
<script type="text/javascript">
function ajax(){
var request=new XMLHttpRequest();
request.open("GET","./doajax.php",true);
request.send();
request.onreadystatechange=function(){
if(request.readyState===4 && request.status===200){
var response=request.responseText;
alert(response);
}
}
}
</script>
</body>
</html>
后端(如果需要传递数据到前端页面的话应该使用echo语句):
<?php
echo 'hello php';
?>
注:为了支持更多的浏览器,可以先判断浏览器是否有XMLHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status返回代码
200: "OK"
404: 未找到页面
Ajax的POST形式进行数据交互
前端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax的POST简易使用</title>
</head>
<body>
<button onclick="ajax()">获取信息</button>
<script type="text/javascript">
function ajax(){
var request=new XMLHttpRequest();
request.open("POST","./doajax.php",true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var data="name=lwqbrell&age=22&sex=boy";
request.send(data);
request.onreadystatechange=function(){
if(request.readyState===4 && request.status===200){
var response=request.responseText;
alert(response);
}
}
}
</script>
</body>
</html>
后端:
<?php
$name=$_POST['name'];
$age=$_POST['age'];
$sex=$_POST['sex'];
echo $name;
echo $age;
echo $sex;
?>