您的位置:首页 > Web前端 > JavaScript

Ajax返回html和json格式数据

2015-10-17 12:49 633 查看
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>';
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: