>  기사  >  백엔드 개발  >  PHP 매개변수 전달 방법 1--ajax

PHP 매개변수 전달 방법 1--ajax

WBOY
WBOY원래의
2016-07-29 09:15:051016검색

ajax는 "A동기 Javascript 및 XML"(비동기 JavaScript 및 XML)이며 생성을 나타냅니다. 대화형 웹 애플리케이션을 위한 웹 개발 기술입니다.

ajax = 비동기식 JavaScript 및 XML(Standard Universal Markup Language의 하위 집합).

ajax는 빠르고 동적인 웹페이지를 만드는 기술입니다.

ajax는 백그라운드에서 서버와 소량의 데이터를 교환하여 웹페이지를 비동기적으로 업데이트할 수 있습니다. 이는 전체 페이지를 다시 로드하지 않고도 웹페이지의 일부를 업데이트할 수 있음을 의미합니다.

기존 웹페이지(ajax를 사용하지 않음)에서는 콘텐츠를 업데이트해야 하는 경우 전체 웹페이지를 다시 로드해야 합니다. 비동기 요청(XMLHttpRequestObject), 부분 새로 고침(본질적으로 js dom)

ajax도 양식을 작성할 때 사용자 이름이 반복되는지 자동으로 결정하는 데 사용됩니다. , 예를 들어 글을 쓰다블로그글을 쓰다가 갑자기 컴퓨터가 다시 시작되면 쓴 내용의 절반을 복원할 수 있습니다.

Get은 단어 제한이 있습니다. 요청은 URL에 포함되며, 서버의 내용을 수정하는 데 사용됩니다.

get은 안전한 요청이며 정보가 수정되지 않았는지 확인해야 합니다.

1. ajax는 일반적으로 현재 페이지에 사용되며 페이지 점프를 구현하지 않습니다.

2. ajax 방법 비동기식 모니터링 서버 측의 상태는 어떻습니까? onreadystatechange를 통해 Readystate 속성 듣기

request.onreadystatechange = function() {

<span>if (request.readyState===4) {</span>
  • 0: 요청이 초기화되지 않았습니다(open()가 아직 호출되지 않았습니다). .
  • 1: 요청이 설정되었지만 아직 전송되지 않았습니다(send()는 아직 호출되지 않았습니다).
  • 2: 요청이 전송되었으며 처리 중입니다(일반적으로 이제 응답에서 콘텐츠 헤더를 얻을 수 있습니다).
  • 3: 요청이 처리되고 있습니다. 일반적으로 응답에 일부 데이터가 있지만 서버가 아직 응답 생성을 완료하지 않았습니다.
  • 4: 응답이 완료되었습니다. 서버의 응답을 가져와 사용할 수 있습니다.

그래서 일반적으로 4와 같다고 판단하여 해당 연산을 수행하게 됩니다.

그러나 이는 요청 상태와 다르다는 점에 유의하세요.

예를 들어, Readystate=4이지만 status=404는 응답이 완료되었지만 응답 내용은 파일이 찾을 수 없습니다

그래서 일반적으로 ==200일 때 내용을 반환하고 그렇지 않으면 사운드 오류를 표시하는 방법이 있습니다.

포스트 요청에서 URL을 인코딩 및 디코딩하도록 URL을 설정해야 합니다. 그렇지 않으면 결과가 올바르게 제공되지 않습니다.

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

그런데 url 디코딩에 문제가 있습니다. urlencode 시 더하기 기호는 자동으로 공백으로 디코딩되므로 &는 변수 커넥터로 디코딩되므로 이러한 문자를 트랜스코딩해야 한다면

(이미지를 캔버스에 업로드하기 위한 URL을 만들 때 이 문제가 발생했습니다)

Pic = Pic.replace(/ /g, "+");
Pic = Pic.replace(/&/g, "&");

3. 서버는 echo를 통해 ajax를 전달하여 인터페이스를 반환합니다.

(팁: zendstudio의 내장 브라우저는 항상 ajax 페이지의 마지막 페이지를 표시하므로 대신 외부 브라우저에서 실행하세요.

기본 설정 - 일반적인 설정 -웹 브라우저.)

간단한 행만 반환하면 Jason이 필요하지 않으며 다른 키 값으로 데이터를 더 편리하게 반환할 수 있습니다.

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

3. 응답 서버 코드 serverjason.php

<?<span>php
</span><span>//</span><span>设置页面内容是html编码格式是utf-8</span><span>header</span>("Content-Type: text/plain;charset=utf-8"<span>); 
</span><span>//</span><span>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"); 

//定义一个多维数组,包含员工的信息,每条员工信息为一个数组</span><span>$staff</span> = <span>array</span><span>    (
        </span><span>array</span>("name" => "洪七", "number" => "101", "sex" => "男", "job" => "总经理"),
        <span>array</span>("name" => "郭靖", "number" => "102", "sex" => "男", "job" => "开发工程师"),
        <span>array</span>("name" => "黄蓉", "number" => "103", "sex" => "女", "job" => "产品经理"<span>)
    );

</span><span>//</span><span>判断如果是get请求,则进行搜索;如果是POST请求,则进行新建
//$_SERVER是一个超<strong>全局变量</strong>,在一个脚本的全部作用域中都可用,不用使用global关键字
//$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法</span><span>if</span> (<span>$_SERVER</span>["REQUEST_METHOD"] == "GET"<span>) {
    search();
} </span><span>elseif</span> (<span>$_SERVER</span>["REQUEST_METHOD"] == "POST"<span>){
    create();
}

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

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

</span>?>

4. 다음은 jQuery의 형태이다

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

<?<span>php
</span><span>//</span><span>设置页面内容是html编码格式是utf-8
//header("Content-Type: text/plain;charset=utf-8"); </span><span>header</span>('Access-Control-Allow-Origin:*'<span>);
</span><span>header</span>('Access-Control-Allow-Methods:POST,GET'<span>);
</span><span>header</span>('Access-Control-Allow-Credentials:true'<span>); 
</span><span>header</span>("Content-Type: application/json;charset=utf-8"<span>); 
</span><span>//</span><span>header("Content-Type: text/xml;charset=utf-8"); 
//header("Content-Type: text/html;charset=utf-8"); 
//header("Content-Type: application/javascript;charset=utf-8"); 

//定义一个多维数组,包含员工的信息,每条员工信息为一个数组</span><span>$staff</span> = <span>array</span><span>    (
        </span><span>array</span>("name" => "洪七", "number" => "101", "sex" => "男", "job" => "总经理"),
        <span>array</span>("name" => "郭靖", "number" => "102", "sex" => "男", "job" => "开发工程师"),
        <span>array</span>("name" => "黄蓉", "number" => "103", "sex" => "女", "job" => "产品经理"<span>)
    );

</span><span>//</span><span>判断如果是get请求,则进行搜索;如果是POST请求,则进行新建
//$_SERVER是一个超<strong>全局变量</strong>,在一个脚本的全部作用域中都可用,不用使用global关键字
//$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法</span><span>if</span> (<span>$_SERVER</span>["REQUEST_METHOD"] == "GET"<span>) {
    search();
} </span><span>elseif</span> (<span>$_SERVER</span>["REQUEST_METHOD"] == "POST"<span>){
    create();
}

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

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

</span>?>

위 내용은 PHP 매개변수 전달 방식 1-ajax를 관련 내용을 포함하여 소개한 내용으로, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되었으면 좋겠습니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.