Ajax combined with PHP collation review

Source: Internet
Author: User

The main function of Ajax is to implement the browser-side asynchronous access to the server: through the browser's XMLHttpRequest object to emit a small amount of data,
Interacting with the server, the server returns a small amount of data and then updates some of the client's pages.

is a request for success information

Front-End Code:

//Get TriggerLet search = document.getElementById (' Search ');//get submitted form datalet keyword = document.getElementById (' keyword ');//Post TriggerLet save = document.getElementById (' Save ');//post-submitted form dataLet Staffname = document.getElementById (' Staffname '); let Staffnumber= document.getElementById (' Staffnumber '); let Staffsex= document.getElementById (' Staffsex '); let Staffjob= document.getElementById (' Staffjob ');//Return Information Demo presentationLet SearchResult = document.getElementById (' SearchResult '); let Creatresult= document.getElementById (' Creatresult ');//GET RequestSearch.addeventlistener (' click ', () ={Let request=NewXMLHttpRequest (); Request.open (' GET ', ' service.php?number=${keyword.value} '); Request.send (NULL); Request.addeventlistener (' ReadyStateChange ', () = {    if(Request.readystate = = = 4 && request.status = = 200) {      //JSON object returned in background to JS object      //using Json.parse (Request.responsetext) When working with JSON does not perform the JS script in JSON is more secure than eval ()Let Jsondata =Json.parse (Request.responsetext); //determine if the error message requires and background convention a JSON object      if(jsondata.success) {Searchresult.innertext=jsondata.msg; } Else{Searchresult.innertext=jsondata.msg; }    }  })})//POST RequestSave.addeventlistener (' click ', () ={Let request=NewXMLHttpRequest (); Request.open (' POST ', ' service.php '); //Post must set the value of Content-type between open and sendRequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); //construct the form data to send and then submit it with SendLet data = ' name=${staffname.value}&number=${staffnumber.value}&sex=${staffsex.value}&job=${staffjob.value} ';  Request.send (data); Request.addeventlistener (' ReadyStateChange ', () = {    if(Request.readystate = = = 4 && request.status = = 200) {      //JSON object returned in background to JS object      //using Json.parse (Request.responsetext) When working with JSON does not perform the JS script in JSON is more secure than eval ()Let Jsondata =Json.parse (Request.responsetext); //determine if the error message requires and background convention a JSON object      if(jsondata.success) {Creatresult.innertext=jsondata.msg; } Else{Creatresult.innertext=jsondata.msg; }    }  })})

Background PHP Code:

<?PHP//set page content encoding format utf-8//header ("Content-type:text/plain;charset=utf-8");//Response format plain textHeader("Content-type:application/json;charset=utf-8");//The format returned by the server is a JSON string//cross-Domain header (' access-control-allow-origin:* ');//Allow all sources to access//cross-Domain header (' Access-control-allow-method:post,get ');//Allow access to the way//header ("Content-type:text/xml;charset=utf-8");//header (" Content-type:text/html;charset=utf-8 ");//header (" Content-type:application/javascript;charset=utf-8 ");// Defines a multidimensional array that contains employee information, each employee information as an array$staff=Array  (    Array("Name" = "Hong Qi", "Number" and "101", "sex" = "male", "job" and "General manager"),Array("Name" = "Guo Jing", "number" = "102", "sex" = "male", "job" and "Development Engineer"),Array("Name" = "Huang Rong", "number" = "103", "sex" = "female", "job" and "Product manager")  );//determines if a GET request is searched; if it is a POST request, the new//$_server is a super global variable that is available in all scopes of a script without using the Global keyword//$_server["request_method "] Returns the request method used by the access pageif($_server["Request_method"]== "GET") {search ();//Search}ElseIf($_server["Request_method"]== "POST") {Create ();//New}//search Functionfunctionsearch () {//append $jsonp =$_get["callback123" when cross-domain request; Hyper Global Variables $_get and $_post are used to collect form data//detection URLs with no number field  if(!isset($_get["number"]) | |Empty($_get["Number"])){    //returns the JSON object below the client if no value is passed    Echo' {' success ': false, ' msg ': ' Please enter employee number '} '; return; }  //variables declared outside the function have global scope and can only be accessed outside of the function. Global keywords are used to access variables within functions  Global $staff; //the number field that the browser passes over  $number=$_get["Number"]; $result= ' {' success ': false, ' msg ': ' No employee found. "}‘; //cross-domain requests are changed to $result = $jsonp. ' ({"Success": false, "MSG": "No employee found.  "})‘; Iterates over $staff multidimensional arrays, finds whether an employee with a key value of number exists, modifies and returns the result if it exists  foreach($staff  as $value) {    if($value["Number"]==$number){      $result= ' {' Success ': true, ' msg ': ' Find Employee: Employee Number: '.$value["Number"]. ', Employee Name: '.$value["Name"]. ', Employee Gender: '.$value["Sex"]. ', employee Position: '.$value["Job"]. ‘"}‘;  Break; }  }  Echo $result;//return Results}//Create an employeefunctionCreate () {//Determine if the information is complete//if the name value is not found or the value is NULL, the return parameter error message is not complete  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"])){    //returns the client's JSON object when the parameter is not aligned    Echo' {' success ': false, ' msg ': ' Employee information not complete '} '; return; }  //TODO: Get post form data and save to database//otherwise prompt save successful  /*echo "Employees:". $_post["Name"]. " Information saved successfully! ";*/  Echo' {' success ': true, ' msg ': ' Employee: '.$_post["Name"]. ' Information saved successfully! "}‘;}?>

Ajax combined with PHP collation review

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.