JSON对象和JSON字符串

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON.parse()</title>
<script type="text/javascript">
	//示例1:此示例使用 JSON.parse 将 JSON 字符串转换为对象
	var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';//JSON 字符串
	var contact = JSON.parse(jsontext);
	document.write(contact.surname + ", " + contact.firstname + ", "+ contact.phone);

	//示例2:和实例1是一样的效果
	var jsontext2 = {"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]};//JSON 对象
	//var contact2 = JSON.parse(jsontext2);
	document.write("<br /><br />"+jsontext2.surname + ", " + jsontext2.firstname + ", "+ jsontext2.phone);
</script>
</head>
<body>
</body>
</html>

输出:

Aaberg, Jesper, 555-0100,555-0120

Aaberg, Jesper, 555-0100,555-0120


************************************************************************************

前端页面接收JSON对象的实例:

<script>	
	sendRecord('1');
	function sendRecord(record){
		var req = {
			user_id:<?php echo $userId;?>,
			record:record,
		}
		$.ajax({
			url: "/3G/wall/ajax_send_record/",
			type:"post",
			data:req,
			dataType:"JSON", //返回数据格式为JSON对象
			success: function(res){
				if(res.result==1){  //因为传递过来是JSON对象,所以不用<span style="font-family:Simsun;">JSON.parse()解析</span>
					alert('11');
				}else if(res.result==2){
					alert('22');
				}else if(res.result==3){
					alert('33');
				}
			},
			error: function(){
				alert('error000');
				console.log(this);
			}
		});
	}
</script>


<?php
    function ajax_send_record()
    {
        $record = $_POST('record');
        
		if ($record==1) {                    
			$json['result'] = 1;                    
		}elseif($record==2){
			$json['result'] = 2;
		}elseif(elseif($record==3){
			$json['result'] = 3;
		}

		$json = json_encode($json);
		echo $json;
    }
?>


JSON对象和JSON字符串,布布扣,bubuko.com

JSON对象和JSON字符串

上一篇:JS绑定事件和移除事件的处理方法


下一篇:浅谈asp.net通过本机cookie仿百度(google)实现搜索input框自动弹出搜索提示