• Ajax返回html和json格式数据


    Ajax可以返回text和xml格式
    可以用Ajax返回大段的html文本和json格式的字符串,然后用eval()方法
    转化为json对象
    php中的json编码:json_encode();
    php中的json解码:json_decode();
    


    前端页面

    <!doctype html>
    <html lang="en">
     <head>
      <meta charset="UTF-8">
      <meta name="Generator" content="EditPlus®">
      <meta name="Author" content="">
      <meta name="Keywords" content="">
      <meta name="Description" content="">
      <title>Document</title>
      <script type="text/javascript">
      function returnjson(){
    	  var xhr=new XMLHttpRequest();
    	  xhr.open('GET','./01.php',true);
    	  xhr.onreadystatechange=function (){
    		if(this.readyState==4){
    			//直接接收是有规律的字符串
    			//alert(this.responseText);
    			var json=eval('('+this.responseText+')');
    			var str='名字:'+json.name+"<br/>";
    			str=str+'年龄:'+json.age+"<br/>";
    			document.getElementById('json').innerHTML=str;
    		}
    	  }
    	  xhr.send(null);
      }
      function returnhtml(){
    	  var xhr=new XMLHttpRequest();
    	  xhr.open('GET','./02.php',true);
    	  xhr.onreadystatechange=function (){
    		if(this.readyState==4){
    			document.getElementById('html').innerHTML=this.responseText;
    		}
    	  }
    	  xhr.send(null);
      }
      </script>
     </head>
     <body>
      <form>
      <input type="button" value="返回json格式数据" onclick="returnjson();"/>
      <input type="button" value="返回html格式数据" onclick="returnhtml();"/>
    	<div id="json">这里显示返回json的信息</div>
      <div id="html">这里显示返回html的信息</div>
      <form>
     </body>
    </html>
    

     01.php

    <?php
    //可以从数据库中取数据
    
    ?>
    {name:'lisi',age:18}
    

     02.php

    <?php
    //从数据库中取出数据,用php打印成html代码
    $arr=array('数据1','数据2','数据3');
    foreach($arr as $v){
    	echo '<li>'.$v.'</li>';
    }
    ?>
    
  • 相关阅读:
    codeforces 459 B.Pashmak and Flowers 解题报告
    poj 1789 Truck History 解题报告
    poj 1258 Agri-Net 解题报告
    poj 1860 Currency Exchange 解题报告
    poj 1094 Sorting It All Out 解题报告
    poj 3368 Frequent values 解题报告
    hdu 1548 A strange lift 解题报告
    BestCoder4 1002 Miaomiao's Geometry (hdu 4932) 解题报告
    hdu 1400 Mondriaan's Dream 解题报告
    打电话主要代码(意图用法)
  • 原文地址:https://www.cnblogs.com/lzzhuany/p/4887310.html
Copyright © 2020-2023  润新知