PHP编程实战15-16/17

前端

<!--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 请求从服务器加载数据,并把返回的数据放置到指定的元素中。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容