Ajax封装
发布时间:2020-12-16 01:41:05 所属栏目:百科 来源:网络整理
导读:本示例封装了ajax函数,将ajax所需参数都写到了一个options变量中, 运行时,先点击请求按钮,请求服务器数据,再点击显示按钮,将请求的数据显示到文本框中。 index.html文件代码如下: !DOCTYPE html html lang = "en" head meta charset = "UTF-8" title
本示例封装了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); } ?>
运行视图如下: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |