php与html简单的json交互示例


前端(HTML)代码


<html>
<head>
    <title>前台处理json简单示例title>
    <meta charset="utf-8"/>
    <script type="text/javascript" src="jquery-1.11.3.min.js">script>
    <script type="text/javascript">
        $("document").ready(function(){
            var url = "server2.php";
            var data = {"do":"first"};
            $.getJSON(url,data,function(res){
                $("#username").val(res.username);
                $("#password").val(res.password);
            });
            var data = {"do":"second"};
            $.getJSON(url,data,function(res){
                $("#members").val(res[2].username);
            });
        });
    script>
head>
<body>
    <h2>获取用户名和密码h2>
    用户名:<input type="text" name="username" id="username"/><br/>
    密码:<input type="password" name="password" id="password"/>
    <br/>
    <h2>获取会员信息h2>
    <textarea id="members">textarea>
body>
html>

后台(PHP)代码


    // 1.一维
    $member['username'] = "mike";
    $member['password'] = "123";

    // 2.二维
    $members['1']['username'] = "mike_1";
    $members['1']['password'] = "123";
    $members['2']['username'] = "mike_2";
    $members['2']['password'] = "123123";
    $members['2']['address'] = "珠海";

    // 根据前台传过来的请求参数来决定执行什么操作
    $do = $_REQUEST['do'];

    switch ($do) {
        case 'first':
            echo json_encode($member);
            break;

        case 'second':
            echo json_encode($members);
            break;
    }

?>

你可能感兴趣的:(编程开发)