JS——我的第二个AJAX程序

来源:互联网 发布:王者荣耀 刘备 知乎 编辑:程序博客网 时间:2024/06/03 12:04

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>用户名:<input type="text" id="uname"><button onclick="getMsg()">发送请求</button><div id="show"></div><script>function getMsg(){//1. 创建xhrvar xhr = createXhr();console.log(xhr);//2. 创建请求var uname = $("uname").value;xhr.open("GET","04-response.php?uname="+uname+"&upwd=123456",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 @$uname = $_REQUEST["uname"];if($uname == null || $uname == ""){die("uname required");}@$upwd = $_REQUEST["upwd"];if($upwd == null || $upwd == ""){die("upwd required");}echo $uname;echo $upwd;echo "我的第一个AJAX程序";?>



原创粉丝点击