前端
<!--PHP编程实战-->
<!--JSON & Ajax -->
<!--15-17-->
<!--从Ajax请求中加载响应的html文件-->
<html>
<head>
<title>Predator/Prey Example</title>
</head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#predator").click(function(){
$("#response").load("predator_prey.php?type=predator");
})
$("#prey").click(function(){
$("#response").load("predator_prey.php?type=prey")
});
});
</script>
<body>
<button id="predator">Predator</button>
<button id="prey">Prey</button>
<p><strong>Ajax response form PHP:</strong></p>
<div id="response"> </div>
</body>
</html>
后台predator_prey.php
<!--PHP编程实战-->
<!--JSON & Ajax -->
<!--15-16-->
<!--PHP文件选择Predator或Prey动物,并以JSON格式输出,predator_prey.php-->
<?php
error_reporting(E_ALL);
$predators = array("bear", "shark", "lion", "tiger", "eagle", "human", "cat", "wolf"); //食肉动物
$prey = array("salmon", "seal", "gazelle", "rabbit", "cow", "moose", "elk", "turkey");//被捕食者
if (isset($_GET['type'])) {
switch ($_GET['type']) {
case "predator":
print json_encode($predators[array_rand($predators)]);
break;
case "prey":
print json_encode($prey[array_rand($prey)]);
break;
default:
print json_encode("n/a");
break;
}
}
?>
重点
- load() 方法通过 AJAX 请求从服务器加载数据,并把返回的数据放置到指定的元素中。