PHP parameter passing method 1--ajax

WBOY
Release: 2016-07-29 09:15:05
Original
896 people have browsed it

ajax stands for "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications.

ajax = Asynchronous JavaScript and XML (a subset of Standard Generalized Markup Language).

ajax is a technology used to create fast and dynamic web pages.

By exchanging a small amount of data with the server in the background, ajax can make web pages update asynchronously. This means that parts of a web page can be updated without reloading the entire page.

Traditional web pages (without using ajax) must reload the entire web page if content needs to be updated. Asynchronous request (XMLHttpRequest object), partial refresh (essentially js dom)

ajax is also used to automatically determine whether the user name is repeated when filling in the form. For example, when you writeblog halfway through writing, the computer suddenly restarts Now, you can restore half of what you wrote.

get is used to obtain data, there is a word limit, the request is included in the URL, post is unlimited, and is used to modify the content of the server.

Get is a safe request and you need to ensure that the information is not modified.

1, ajax is generally used for the current page and does not implement page jumps

2, ajaxside: How to asynchronously monitor the status of the server side? Listening to the readystate attribute through onreadystatechange

request.onreadystatechange = function() {

if (request.readyState===4) {
Copy after login
  • 0: The request is not initialized (open() has not been called yet).
  • 1: The request has been established, but has not been sent yet (send() has not been called yet).
  • 2: The request has been sent and is being processed (usually the content headers can now be obtained from the response).
  • 3: The request is being processed; usually some data is available in the response, but the server has not yet completed generating the response.
  • 4: The response is complete; you can get and use the server's response.

So generally the corresponding operation is performed after judging that it is equal to 4.

But note that this is different from the status of the request

For example, readystate=4 but status=404 means that the response is completed but the content of the response is that the file is not found

So the general approach is to return the content when ==200, and the rest is Just show the pronunciation error.

Please note that in the post request, you must set the url to encode and decode the url, otherwise the result will not be given correctly

request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

But there is a problem with url decoding. Since the plus sign will be automatically decoded into a space when urlencoded, & will be decoded into a variable connector, so if these characters appear, they must be transcoded

(when uploading images on canvas I encountered this problem when using the url)

Pic = Pic.replace(/+/g, "%2B");
Pic = Pic.replace(/&/g, "%26");

3. The server returns the interface passed ajax through echo.

(Tip: zendstudio’s built-in browser will always display the last page for ajax pages, so run it in an external browser instead

Settings in the preference-general-web browser.)

If you only Returning a simple row does not require Jason. Jason can more conveniently return data with different key values.

 1DOCTYPE HTML> 2<html> 3<head> 4<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5<title>Demotitle> 6<style> 7body, input, select, button, h1 { 8    font-size: 28px; 9    line-height:1.7;10}11style>12head>1314<body>1516<h1>员工查询h1>1718<label>请输入员工编号:label>19<input type="text" id="keyword"/>20<button id="search">查询button>21<p id="searchResult">p>2223<h1>员工新建h1>24<label>请输入员工姓名:label>25<input type="text" id="staffName"/><br>26<label>请输入员工编号:label>27<input type="text" id="staffNumber"/><br>28<label>请选择员工性别:label>29<select id="staffSex">30<option>option>31<option>option>32select><br>33<label>请输入员工职位:label>34<input type="text" id="staffJob"/><br>35<button id="save">保存button>36<p id="createResult">p>3738<script>39document.getElementById("search").onclick =function() { 
40var request =new XMLHttpRequest();
41    request.open("GET", "serverjson.php?number="+ document.getElementById("keyword").value);
42    request.send();
43    request.onreadystatechange =function() {
44if (request.readyState===4) {
45if (request.status===200) { //不同的status在百度可以找到46var data = JSON.parse(request.responseText);//json.parse!47if (data.success) { //注意seccess也返回jason的一个键值48                    document.getElementById("searchResult").innerHTML = data.msg;//json中的msg键值49                } else {
50                    document.getElementById("searchResult").innerHTML ="出现错误:"+ data.msg;
51                }
52            } else {
53 alert("发生错误:"+ request.status); 54 } 55 } 56 } 57} 5859document.getElementById("save").onclick =function() { 60var request =new XMLHttpRequest(); 61 request.open("POST", "serverjson.php"); 62var data ="name="+ document.getElementById("staffName").value 63+"&number="+ document.getElementById("staffNumber").value 64+"&sex="+ document.getElementById("staffSex").value 65+"&job="+ document.getElementById("staffJob").value; 66 request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 67 request.send(data); 68 request.onreadystatechange =function() { 69if (request.readyState===4) { 70if (request.status===200) { 71var data = JSON.parse(request.responseText); 72if (data.success) { 73 document.getElementById("createResult").innerHTML = data.msg; 74 } else { 75 document.getElementById("createResult").innerHTML ="出现错误:"+ data.msg; 76 } 77 } else { 78 alert("发生错误:"+ request.status); 79 } 80 } 81 } 82} 83script>84body>85html>
Copy after login

3. Response server code serverjason.php

php
//设置页面内容是html编码格式是utf-8header("Content-Type: text/plain;charset=utf-8"); 
//header("Content-Type: application/json;charset=utf-8"); 
//header("Content-Type: text/xml;charset=utf-8"); 
//header("Content-Type: text/html;charset=utf-8"); 
//header("Content-Type: application/javascript;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请求,则进行新建
//$_SERVER是一个超全局变量,在一个脚本的全部作用域中都可用,不用使用global关键字
//$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法if ($_SERVER["REQUEST_METHOD"] == "GET") {
    search();
} elseif ($_SERVER["REQUEST_METHOD"] == "POST"){
    create();
}

//通过员工编号搜索员工function search(){
    //检查是否有员工编号的参数
    //isset检测变量是否设置;empty判断值为否为空
    //超全局变量 $_GET 和 $_POST 用于收集表单数据if (!isset($_GET["number"]) || empty($_GET["number"])) {
        echo '{"success":false,"msg":"参数错误"}';//jason格式return;
    }
    //函数之外声明的变量拥有 Global 作用域,只能在函数以外进行访问。
    //global 关键词用于访问函数内的全局变量global$staff;
    //获取number参数$number = $_GET["number"];
    $result = '{"success":false,"msg":"没有找到员工。"}';
    
    //遍历$staff多维数组,查找key值为number的员工是否存在,如果存在,则修改返回结果foreach ($staffas$value) {
        if ($value["number"] == $number) {
            $result = '{"success":true,"msg":"找到员工:员工编号:' . $value["number"] . 
                            ',员工姓名:' . $value["name"] . 
                            ',员工性别:' . $value["sex"] . 
                            ',员工职位:' . $value["job"] . '"}';//jason格式break;
        }
    }
    echo$result;
}

//创建员工function create(){
    //判断信息是否填写完全if (!isset($_POST["name"]) || empty($_POST["name"])
        || !isset($_POST["number"]) || empty($_POST["number"])
        || !isset($_POST["sex"]) || empty($_POST["sex"])
        || !isset($_POST["job"]) || empty($_POST["job"])) {
        echo '{"success":false,"msg":"参数错误,员工信息填写不全"}';
        return;
    }
    //TODO: 获取POST表单数据并保存到数据库
    
    //提示保存成功echo '{"success":true,"msg":"员工:' . $_POST["name"] . ' 信息保存成功!"}';
}

?>
Copy after login

4. The following is the form of jQuery

DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Demotitle><style>body, input, select, button, h1 {    font-size: 28px;    line-height:1.7;}style>head><body><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="staffName"/><br><label>请输入员工编号:label><input type="text" id="staffNumber"/><br><label>请选择员工性别:label><select id="staffSex"><option>option><option>option>select><br><label>请输入员工职位:label><input type="text" id="staffJob"/><br><button id="save">保存button><p id="createResult">p><script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js">script><script>$(document).ready(function(){ 
    $("#search").click(function(){ 
        $.ajax({ 
            type: "GET",     
            url: "serverjson2.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);  
            },     
        });
    });
    
    $("#save").click(function(){ 
        $.ajax({ 
            type: "POST",     
            url: "serverjson.php",
            data: {
                name: $("#staffName").val(), 
                number: $("#staffNumber").val(), 
                sex: $("#staffSex").val(), 
                job: $("#staffJob").val()
            },
            dataType: "json",
            success: function(data){
                if (data.success) { 
                    $("#createResult").html(data.msg);
                } else {
                    $("#createResult").html("出现错误:"+ data.msg);
                }  
            },
            error: function(jqXHR){     
               alert("发生错误:"+ jqXHR.status);  
            },     
        });
    });
});
script>body>html>
Copy after login

php
//设置页面内容是html编码格式是utf-8
//header("Content-Type: text/plain;charset=utf-8"); header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET');
header('Access-Control-Allow-Credentials:true'); 
header("Content-Type: application/json;charset=utf-8"); 
//header("Content-Type: text/xml;charset=utf-8"); 
//header("Content-Type: text/html;charset=utf-8"); 
//header("Content-Type: application/javascript;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请求,则进行新建
//$_SERVER是一个超全局变量,在一个脚本的全部作用域中都可用,不用使用global关键字
//$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法if ($_SERVER["REQUEST_METHOD"] == "GET") {
    search();
} elseif ($_SERVER["REQUEST_METHOD"] == "POST"){
    create();
}

//通过员工编号搜索员工function search(){
    //检查是否有员工编号的参数
    //isset检测变量是否设置;empty判断值为否为空
    //超全局变量 $_GET 和 $_POST 用于收集表单数据if (!isset($_GET["number"]) || empty($_GET["number"])) {
        echo '{"success":false,"msg":"参数错误"}';
        return;
    }
    //函数之外声明的变量拥有 Global 作用域,只能在函数以外进行访问。
    //global 关键词用于访问函数内的全局变量global$staff;
    //获取number参数$number = $_GET["number"];
    $result = '{"success":false,"msg":"没有找到员工。"}';
    
    //遍历$staff多维数组,查找key值为number的员工是否存在,如果存在,则修改返回结果foreach ($staffas$value) {
        if ($value["number"] == $number) {
            $result = '{"success":true,"msg":"找到员工:员工编号:' . $value["number"] . 
                            ',员工姓名:' . $value["name"] . 
                            ',员工性别:' . $value["sex"] . 
                            ',员工职位:' . $value["job"] . '"}';
            break;
        }
    }
    echo$result;
}

//创建员工function create(){
    //判断信息是否填写完全if (!isset($_POST["name"]) || empty($_POST["name"])
        || !isset($_POST["number"]) || empty($_POST["number"])
        || !isset($_POST["sex"]) || empty($_POST["sex"])
        || !isset($_POST["job"]) || empty($_POST["job"])) {
        echo '{"success":false,"msg":"参数错误,员工信息填写不全"}';
        return;
    }
    //TODO: 获取POST表单数据并保存到数据库
    
    //提示保存成功echo '{"success":true,"msg":"员工:' . $_POST["name"] . ' 信息保存成功!"}';
}

?>
Copy after login

The above introduces the PHP parameter passing method 1-ajax, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!