PHP JSON
0 - 2 - 4
1. JSON是什么?
就是一串有规律的字符。基本格式是{"foo":"bar"}
2. JSON GET请求例子。
服务器端:
time.php
<?php echo json_encode(microtime(true));
客户端:
<head> <script type="text/javascript" src="json.js"></script> <script type="text/javascript"> function getXHR(){ var req; if(window.XMLHttpRequest){ req = new XMLHttpRequest(); }else if(window.ActiveXObject){ req = new ActiveXObject("Microsoft.XMLHTTP"); } return req; } function getServerTime(){ xhr = getXHR(); rand = Math.random(1); //id设置成rand是为了避免Ajax URL的HTTP缓存。 url = "http://localhost/test/time.php?id="+rand; //false为同步(阻塞)模式 xhr.open("GET",url,false); xhr.send(); json = xhr.responseText; time = json.parseJSON(); div = document.getElementById("jsonData"); div.innerHTML = time; } </script> </head> <body> <a href="#" onclick="getServerTime()">Show JSON Data</a> <div id="jsonData"></div> </body>
3. JSON POST请求例子。
服务器端:
suggest.php
<?php $arr = array('Alpha','Bravo','X-RAY','test','echo','taitai','eee'); $search = strtolower($_POST['search']); $hits = array(); if(!empty($search)){ foreach($arr as $name){ if(strpos(strtolower($name),$search) === 0){ $hits[] = $name; } } } echo json_encode($hits);
客户端:
<head> <script type="text/javascript" src="json.js"></script> <script type="text/javascript"> var xhr; function getXHR(){ var req; if(window.XMLHttpRequest){ req = new XMLHttpRequest(); }else if(window.ActiveXObject){ req = new ActiveXObject("Microsoft.XMLHTTP"); } return req; } function suggest(){ //如果还有未处理完的XHR请求正在进行,就中断它 if(xhr && xhr.readyState != 0){ xhr.abort(); } xhr = getXHR(); //创建异步POST请求 xhr.open("POST","http://localhost/test/suggest.php",true); //读取搜索值 searchValue = document.getElementById("search").value; //以URL编码格式编码数据 data = "search="+encodeURIComponent(searchValue); //定义接收状态变更通知的函数 xhr.onreadystatechange = readyStateChange; //设置请求头信息,以便让PHP知道这是一个表单提交 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //将数据传送到服务器上 xhr.send(data); } function readyStateChange(){ //状态4表示数据已经准备好了 if(xhr.readyState == 4){ //检查服务器是否发送了数据,并且请求是200 if(xhr.responseText && xhr.status == 200){ json = xhr.responseText; //解析服务器的响应内容,创建一个JS数组 try{ suggestionArr = json.parseJSON(); }catch(e){ //解析JSON数据时遇到的问题 } //创建一些HTML文件 tmpHtml = ""; for(i=0,len=suggestionArr.length;i<len;i++){ tmpHtml += suggestionArr[i] + "<br/>"; } div = document.getElementById("suggestions"); div.innerHTML = tmpHtml; }//或者是空响应,404请求等情况 } } </script> </head> <body> <input id="search" type="text" onkeyup="suggest()"/> <div id="suggestions"></div> </body>