AJAX-----04XMLHttpRequest对象的ajax

时间:2022-05-22 02:36:16

AJAX-----04XMLHttpRequest对象的ajax

AJAX-----04XMLHttpRequest对象的ajax

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function createXHR(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
} function vote(){
//创建xhr
var xhr = createXHR();
//打开链接
xhr.open('get','4.php',true);
//发送请求
xhr.send(null); xhr.onreadystatechange = function(){
if(this.readyState == 4){
if(this.responseText == '1'){
document.getElementById('tp').innerHTML = this.responseText;
}else if(this.responseText == '0'){
document.getElementById('tp').innerHTML = this.responseText;
}else{
document.getElementById('tp').innerHTML = this.responseText;
}
}
}
}
</script>
</head>
<body>
<div>
<p>红烧牛肉</p>
<p><input type="button" value='投票' onclick="vote();"></p>
</div>
<div id="tp"></div>
</body>
</html>

AJAX-----04XMLHttpRequest对象的ajax

<?php
sleep(2);
if(rand(1,10)<4){
echo '0';
}else{
$con = file_get_contents('4res.txt');
$con += 1;
file_put_contents('4res.txt',$con);
//该值返回给前端
//this.responseText用这属性即可接收
echo '10';
}