要玩json首先就需要知道一般都数据是怎么处理的:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function createXHR(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else if(window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } return xhr; } function test1(){ var xhr = createXHR(); xhr.open('GET','8.php',true); xhr.onreadystatechange = function(){ if(this.readyState == 4){ document.getElementById('lists').innerHTML = this.responseText; } } xhr.send(null); } </script> </head> <body> <input type="button" value="更新歌曲" onclick="test1();"> <div id="lists"></div> </body> </html>
<?php header("Content-Type:text/html;charset=utf-8"); foreach( array('夜夜十八摸','人狗情未了主题曲','左手右手慢动作','妹妹坐船头') as $v ){ echo '<li>'.$v.'</li>'; }
我们居然知道普通数据是怎么处理的了,那么json数据其实也是很简单的,不过是设计得比较巧妙,看上去好像很有规律,巧就巧在可以让javascript当对象使用而已。。。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> ul{ list-style:none; } </style> <script> function createXHR(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else if(window.ActiveXObject){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } return xhr; } function test1(){ var xhr = createXHR(); xhr.open('GET','8.php',true); xhr.onreadystatechange = function(){ if(this.readyState == 4){ //alert(this.responseText); var mp3 = eval('('+ this.responseText +')'); document.getElementById('title').innerHTML = mp3.title; document.getElementById('desc').innerHTML = mp3.desc; } } xhr.send(null); } </script> </head> <body> <input type="button" value="更新歌曲" onclick="test1();"> <ul> <li> <p id="title"></p> <p id="desc"></p> </li> </ul> </body> </html>
<?php $mp3 = array('title'=>'夜夜十八摸','desc'=>'男人夜夜都是泪'); echo json_encode($mp3);