Blogger Information
Blog 38
fans 1
comment 0
visits 24251
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月16日模拟获取服务器数据
鲨鱼辣椒的博客
Original
657 people have browsed it

从服务器端获取JSON格式字符串并解决到前端页面中显示

下面是html代码:

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>模拟获取服务器数据</title>
	<style>
		button{
			background-color: cornflowerblue;
		}
		button:hover{
			color: orangered;
		}
		/*#h3-1{*/
		/*display: none;*/
		/*}*/
	</style>
</head>
<body>
<h3 >点击事件模拟获取服务器数据</h3>
<button>点我获取数据</button>
<h3 id="h3-1"></h3>

<script>
	//获取button按钮
	var btn = document.getElementsByTagName('button').item(0);
	//生成一个Ajax对象
	var request = new XMLHttpRequest();
	//给按钮添加事件
	btn.addEventListener('click',getData,false);

	//事件对应函数
	function getData() {
		request.addEventListener('readystatechange',show,false);
		request.open('get','admin/demo1.php',true);
		request.send(null);
	}

	var h3 = document.getElementsByTagName('h3').item(1);
	function show() {
		//
		// if (h3.style.display === "none") {
		//     h3.style.display = "block";
		// } else {
		//     h3.style.display = "none";
		// }

		if (request.readyState === 4){
			var obj = JSON.parse(request.responseText);
			console.log(obj);
			if (h3.style.display === "none") {
				h3.style.display = "block";
				h3.innerHTML = obj.name + ',PHP成绩是: ' + obj.grade.php + ',最喜欢: ' + obj.hobby[1];
			} else {
				h3.style.display = "none";
				h3.innerHTML = '';
			}


		}
	}
</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

php代码模拟服务器数据:

实例

<?php

$json = '{
    "name": "小金莲",
    "age": 23,
    "isMarried": true,
    "sweetheart": null,
    "grade": {
        "javascript": 80,
        "php": 90
    },
    "hobby": ["做烧饼", "下毒", "饮酒作乐"]
}';

echo $json;

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post