本示例封装了ajax函数,将ajax所需参数都写到了一个options变量中,
运行时,先点击请求按钮,请求服务器数据,再点击显示按钮,将请求的数据显示到文本框中。
index.html文件代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{
width: 200px;
height: 200px;
background: red;
}
.special{
border: 5px solid #333;
}
</style>
</head>
<body>
<input type="text" id='username'><br/>
<input type="text" id='password'><br/>
<input type='button' id='btn1' value="请求"/>
<input type='button' id='btn2' value="显示"/>
<script>
var btn1=document.getElementById('btn1');
var btn2=document.getElementById('btn2');
var myname=document.getElementById('username');
var password=document.getElementById('password');
function ajax(url,options,type){
var oAjax=null;
var type=type || "GET";
//alert(type);
if(window.XMLHttpRequest){
oAjax=new XMLHttpRequest();
}
else{
oAjax=new ActiveXObject('Microsoft.XMLHTTP');
}
oAjax.onreadystatechange=function(){
if (oAjax.readyState==4) {
if (oAjax.status==200) {
options.onsuccess(oAjax.responseText);
}
else{
options.onfail();
};
};
}
url=url+"?username="+options.data.username+"&password="+options.data.password+"&t="+Math.random();
oAjax.open(type,url,true);
oAjax.send();
}
var options={
data:{username:"zhaoshaobang",
password:"123456"},
onsuccess:function(str){
btn2.onclick=function(){
var jsondata=eval("("+str+")");
myname.value=jsondata[0];
password.value=jsondata[1];
}
},
onfail:function(){
console.log('failed');
}};
btn1.onclick=function(){
ajax('data.php',options);
}
</script>
</body>
</html>
data.php代码如下:
<?php
if(isset($_GET['username'],$_GET['password'])){
$name=$_GET['username'];
$word=$_GET['password'];
$ary=array($name,$word);
echo json_encode($ary);
}
?>
运行视图如下: