JS——我的第一个AJAX程序

来源:互联网 发布:飞利浦脱毛仪 知乎 编辑:程序博客网 时间:2024/06/05 17:02

common.js

//common.jsfunction $(id){return document.getElementById(id);}var xhr;function createXhr() {if(window.XMLHttpRequest){xhr = new XMLHttpRequest();return xhr;}else{xhr = new ActiveXObject("Microsoft XMLHttp");// Microsoft XMLHttp大小写随意return xhr;}}

index.html

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script src="common.js"></script></head><body><button onclick="getMsg()">发送请求</button><div id="show"></div><script>function getMsg(){//1. 创建xhrvar xhr = createXhr();console.log(xhr);//2. 创建请求xhr.open("GET","04-response.php",true);   //3. 设置回调函数—onreadystatechange   xhr.onreadystatechange = function() {   if(xhr.readyState == 4 && xhr.status == 200){ //status   //接收响应数据   console.log("1111");   var resText = xhr.responseText;   $("show").innerHTML = resText;   console.log(resText);   }   }   //4. 发送请求   xhr.send();}</script></body></html>
04-response.php

<?php echo "我的第一个AJAX程序";?>