<html> <head> <title>用户注册</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <script type="text/javascript"> //创建ajax引擎 function getXmlHttpObject(){ var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } var myXmlHttpRequest=""; //验证用户名是否存在 function checkName(){ myXmlHttpRequest=getXmlHttpObject(); //怎么判断创建ok if(myXmlHttpRequest){ //通过myXmlHttpRequest对象发送请求到服务器的某个页面 //第一个参数表示请求的方式, "get" / "post" //第二个参数指定url,对哪个页面发出ajax请求(本质仍然是http请求) //第三个参数表示 true表示使用异步机制,如果false表示不使用异步 var url="json.php"; var data="username="+$("username").value; //打开请求. myXmlHttpRequest.open("post",url,true); //指定回调函数.stateChanged是函数名 myXmlHttpRequest.onreadystatechange=stateChanged; myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //真的发送请求,如果是get请求则填入 null即可 //如果是post请求,则填入实际的数据 myXmlHttpRequest.send(data); } } //回调函数 function stateChanged(){ //window.alert("处理函数被调回"+myXmlHttpRequest.readyState); //我要取出从registerPro.php页面返回的数据 if(myXmlHttpRequest.readyState==4){ var mes=myXmlHttpRequest.responseText; //取出值,根据返回信息的格式定.text var mes_obj=eval("("+mes+")"); $('myres').value=mes_obj.res;//第一种方式 $('myres').value=mes_obj[0].res;//第二种方式 } } //这里我们写一个函数 function $(id){ return document.getElementById(id); } </script> </head> <body> <form action="???" method="post"> 用户名字:<input type="text" onkeyup="checkName();" name="username1" id="username"><input type="button" onclick="checkName();" value="验证用户名"> <input style="border-width: 0;color: red" type="text" id="myres"> </form> </body> </html>
<?php header("Content-Type: text/html;charset=utf-8"); //告诉浏览器不要缓存数据 header("Cache-Control: no-cache"); $info=""; if($_REQUEST['username']=='lai'){ $info="{'res':'该用户不可以用'}";//第一种方式 $info="[{'res':'该用户不可以用','id':'001'},{'res':'该用户不可以用1','id':'002'}]";//第二种方式}else{ $info="{'res':'该用户可以用'}"; } echo $info;
//复杂方式<script language="JavaScript"> var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }, { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ], "sex":"男" } alert(people.authors[1].genre); // "fantasy" alert(people.musicians[1].lastName); // Clapton alert(people.programmers[2].firstName); // Value is "Elliotte" alert(people.sex); // 男 </script>
来源:https://www.cnblogs.com/MemoryofHeart/archive/2013/04/28/3048767.html