ajax返回json类型的数据,用js处理json类型的数据

5 篇文章 0 订阅
3 篇文章 0 订阅

index_do.php

<?php
header("Content-Type:text/html;charset=utf-8");
header("Cache-Control:no-cache");
	$username=$_POST['username'];
	$info="";
	if ($username=='admin'){
		$info='{"name":"owen","age":"24","sex":"man"}';
	}else {
		$info='{"name":"nancy","age":"23","sex":"woman"}';
	}
	echo $info;
?>

index.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>ajax</title>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
	function $(id){
		return document.getElementById(id);
	}
	function checkName(){
		var http_request=createAjax();
		http_request.onreadystatechange=function(){
			if(http_request.readyState==4 && http_request.status==200){
				var notice=http_request.responseText;
				var notice_obj=eval("("+notice+")");
				$("notice").innerHTML=notice_obj.name;
			}
		}
		var data="username="+$("username").value+"&mytime="+new Date();
		var url="index_do.php";
		http_request.open("post",url,true);
		http_request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		http_request.send(data);
	}
</script>
</head>
<body>
Please enter your username:<input type="text" name="username" id="username" onChange="checkName();" />
<span id="notice"></span>
</body>
</html>

这里用到了eval()函数,将json格式的数据库转换成对象。这样就可以很方便的取出数据。对象属性对应属性值。

var notice=http_request.responseText;


var notice_obj=eval("("+notice+")");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值