PHP与AJAX

一.基础
   1.ajax是什么?
    ajax = Asynchronous JavaScript and XML (异步的JavaScript和XML)
    ajax不是编程语言,ajax是一种用于创建快速动态网页的技术。
2.ajax有什么特点?
    传统的网页如果需要更新,必须重载整个页面,ajax可以实现局部刷新的效果,即向服务器
    请求部分页面所需数据更新网页内容,这样可以减轻服务器的负担。
二.实践
    下面例子实现的是员工信息的查询和创建,其中服务端用的是PHP语言实现的,此处没有使用数
    据库服务,员工信息存在数组中;ajax用了两种方式实现,一种是jQuery,一种是原生方式。

jQuery方式实现

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>php&ajax</title>
    <style type="text/css">
        body,input,button,select,h1{
            font-size: 30px;
            line-height: 1.2;
        }
        div{
            width: 690px;
            margin: auto;
            margin-top: 100px;
        }
    </style>
</head>
<body>
    <div>
        <h1>员工查询</h1>
        <label>请输入员工编号</label>
        <input type="text" id="keyword"/>
        <button id="search">查询</button>
        <p id="searchResult"></p>

        <h1>员工新建</h1>
        <label>请输入员工编号</label>
        <input type="text" id="number"/><br>
        <label>请输入员工姓名</label>
        <input type="text" id="name"/><br>
        <label>请输入员工性别</label>
        <select id="sex">
            <option>男</option>
            <option>女</option>
        </select><br>
        <label>请输入员工职位</label>
        <input type="text" id="job"/>
        <button id="save">保存</button>
        <p id="createResult"></p>
    </div>
<!-- 引入百度的静态资源库 -->
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js"></script>
<script>
    // jquery封装的Ajax请求 GET
    $(document).ready(function(){
        $("#search").click(function(){
            $.ajax({
                type:"GET",
                url:"ajax.php?number="+$("#keyword").val(),
                dataType:"json",
                success:function(data){
                    if (data.success) {
                        $("#searchResult").html(data.msg);
                    }else{
                        $("#searchResult").html("出现错误:"+data.msg);
                    }
                },
                error:function(jqXHR){
                    alert("发生错误:"+jqXHR.status);
                },
            });
        });
    });
    // jquery封装的Ajax请求 GET
    $(document).ready(function(){
        $("#save").click(function(){
            $.ajax({
                type:"POST",
                url:"ajax.php",
                dataType:"json",
                data:{
                    name:$("#name").val(),
                    number:$("#number").val(),
                    sex:$("#sex").val(),
                    job:$("#job").val(),
                },
                success:function(data){
                    if(data.success){
                        $("#createResult").html(data.msg);
                    }else{
                        $("#createResult").html("出现错误:"+data.msg);
                    }
                },
                error:function(jqXHR){
                    alert("发生错误:"+jqXHR.status);
                }
            });
        });
    });
</script>
</body>
</html>

原生代码实现

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>php&ajax</title>
    <style type="text/css">
        body,input,button,select,h1{
            font-size: 30px;
            line-height: 1.2;
        }
        div{
            width: 690px;
            margin: auto;
            margin-top: 100px;
        }
    </style>
</head>
<body>
    <div>
        <h1>员工查询</h1>
        <label>请输入员工编号</label>
        <input type="text" id="keyword"/>
        <button id="search">查询</button>
        <p id="searchResult"></p>

        <h1>员工新建</h1>
        <label>请输入员工编号</label>
        <input type="text" id="number"/><br>
        <label>请输入员工姓名</label>
        <input type="text" id="name"/><br>
        <label>请输入员工性别</label>
        <select id="sex">
            <option>男</option>
            <option>女</option>
        </select><br>
        <label>请输入员工职位</label>
        <input type="text" id="job"/>
        <button id="save">保存</button>
        <p id="createResult"></p>
    </div>
<script>
    //原生js写的Ajax请求
    document.getElementById("search").onclick = function(){
        //发送Ajax查询请求并处理
        var request = new XMLHttpRequest();
        request.open("GET","ajax.php?number="+document.getElementById("keyword").value);
        request.send();
        //监听readystate对象是否发生变化
        request.onreadystatechange=function(){
            if(request.readyState === 4){
                if (request.status === 200) {
                    var data = JSON.parse(request.responseText);
                    if (data.success) {
                        document.getElementById("searchResult").innerHTML = data.msg;
                    }else{
                        document.getElementById("searchResult").innerHTML = '出现错误:'+data.msg;
                    }
                }else{
                    alert("发生错误:"+request.status);
                }
            }
        }
    }

    document.getElementById("save").onclick = function(){
        //发送Ajax查询请求并处理
        var request = new XMLHttpRequest();
        request.open("POST","ajax.php");
        var data = "name="+document.getElementById("name").value
                    +"&number="+document.getElementById("number").value
                    +"&sex="+document.getElementById("sex").value
                    +"&job="+document.getElementById("job").value
        request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        request.send(data);
        console.log(data);
        //监听readystate对象是否发生变化
        request.onreadystatechange=function(){
            if(request.readyState === 4){
                if (request.status === 200) {
                    var data = JSON.parse(request.responseText);
                    if (data.success) {
                        document.getElementById("createResult").innerHTML = data.msg;
                    }else{
                        document.getElementById("createResult").innerHTML = '出现错误:'+data.msg;
                    }
                }else{
                    alert("发生错误:"+request.status);
                }
            }
        }
    }
</script>
</body>
</html>

PHP代码(ajax.php)

<?php
//设置页面内容是HTML 编码格式是utf-8
header("Content-Type:application/json;charset=utf-8");
//定义一个多维数组,存放员工信息
$staff = array(
    array("name" => "洪七公", "number" => "101", "sex" => "男", "job" => "总经理"),
    array("name" => "老顽童", "number" => "102", "sex" => "男", "job" => "董事长"),
    array("name" => "欧阳锋", "number" => "103", "sex" => "男", "job" => "工程师"),
);
//判断如果是get请求,则调用搜索函数;如果是post请求,则调用新建函数
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    search();
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
    create();
}
/**
 * 通过员工编号搜索员工
 **/
function search()
{
    if (!isset($_GET['number']) || empty($_GET['number'])) {
        show(-1, '参数错误');
        return;
    }
    global $staff;
    $number = $_GET['number'];
    $result = '没有找到员工';
    foreach ($staff as $value) {
        if (in_array($number, $value)) {
            $result = '姓名:' . $value['name'] . ',性别:' . $value['sex'] . ',编号:' . $value['number'] . ',职位:' . $value['job'];
            break;
        }
    }
    show(1, $result);
    return;
}
/**
 * 新建员工信息
 **/
function create()
{
    $name   = !empty($_POST['name']) ? $_POST['name'] : '';
    $sex    = !empty($_POST['sex']) ? $_POST['sex'] : '';
    $number = !empty($_POST['number']) ? $_POST['number'] : '';
    $job    = !empty($_POST['job']) ? $_POST['job'] : '';
    if (empty($name) || empty($sex) || empty($number) || empty($job)) {
        show(-1, '信息不全');
    } else {
        $res = $name . ' 的信息保存成功!';
        show(1, $res);
    }
    return;
}
/**
 * json形式输出展示信息
 * @param $code
 * @param $msg
 **/
function show($code = '', $msg = '')
{
    if ($code === 1) {
        echo '{"success":true,"msg":"' . $msg . '"}';
    } else {
        echo '{"success":false,"msg":"' . $msg . '"}';
    }
    return;
}

三.总结
    Ajax虽然不是编程语言,但是Ajax技术的实现还是需要用js脚本编写的,
    所以编写脚本的时候,还是要注意JavaScript的语法规则,避免出现一些低级错误

原文地址:https://www.cnblogs.com/chengzi-he/p/8932217.html