This article is mainly for everyone to introduce the JS and JSON to implement the Ajax simple example of the relevant data, with a certain reference value, interested in small partners can refer to, hope to help everyone.
Pre-preparation
1, install Wampserver or other similar software to build the local integrated installation environment, I installed the Phpstudy
2, HTML, JS, CSS and other files need to be placed in the Phpstudy www directory, the default run index page
3, Bootstrap.css
Interface:
Phpstudy is very convenient to use, if your computer has not installed PHP, it is important to configure the system environment variables, Php.exe (in the installation directory phpstudy) to add the path, and then in the cmd input php-v, Information such as the installation version of PHP indicates that the installation was successful.
Then create a new project under the WWW folder of Phpstudy, here I named Ajaxdemo.
Index.html
<! DOCTYPE html>
Staffmanage.js
The instantiation of Ajax can be divided into five points, which is very good to remember:
1. New one XMLHttpRequest instance
Note compatible with the lower version of IE browser
var xhr; if (window. XMLHttpRequest) {xhr= new XMLHttpRequest ();} else {xhr= new ActiveXObject (' Microsoft.XMLHTTP ');}
2. Open (Method,url,asyn)
The open () method of the XMLHttpRequest object has 3 parameters, the first parameter specifies whether it is get or post, the second parameter specifies the URL address, the third parameter specifies if async is used, and the default is true, so no writing is necessary.
If the POST request also add the request header setRequestHeader ("Content-type", "application/x-www-form-urlencoded")
4. Send
The Send () method is called to actually send the request. The GET request does not require arguments, and the POST request requires the body part to be passed in as a string or Formdata object.
5, onReadyStateChange
6, ResponseText
Query Employee method var okeyword=document.getelementbyid (' keyword '),//Employee number Osearchbtn=document.getelementbyid (' Search ') ,//Query button Osearchres=document.getelementbyid (' SearchResult '); Feedback results Display//Query Employee button click event Osearchbtn.onclick=function () {searchstaff (); }//Create Query Employee method function Searchstaff () {//var xhr=new xmlhttprequest (); Standard writing and IE mix together, can be compatible with the low version of IE browser var xhr; if (window. XMLHttpRequest) {xhr= new XMLHttpRequest (); } else {xhr= new ActiveXObject (' microsoft.xmlhttp '); } xhr.open (' GET ', ' serverjson.php?number= ' +okeyword.value); Xhr.send (); After you have created the XMLHttpRequest object, set the callback function for onreadystatechange first. In the callback function, we usually only need to readystate = = 4 to determine whether the request is complete, if it is completed, and then according to status = = 200 to determine whether it is a successful response. Xhr.onreadystatechange=function () {if (xhr.readystate==4) {if (xhr.status=200) {var data=json.par SE (Xhr.responsetext); JSON parsing method Json.parse or eval (' (' +xhr.responsetext+ ') ') Osearchres.innerhtml=data.msg; }}}//Increase employee Var Oaddnumber=document.getelementbyid (' Add-number '),//employee number Oaddname=docume Nt.getelementbyid (' Add-name '),//Employee name Oaddsex=document.getelementbyid (' Add-sex '),//employee gender Oaddjob=document.getele Mentbyid (' add-job '),//Employee position Oaddsearch=document.getelementbyid (' add-search '),//Add Employee button Oaddresult=document.getel Ementbyid (' add-resultshow '); Feedback results show//Add Employee button click event Oaddsearch.onclick=function () {createstaff (); }//Create Add Employee Method function Createstaff () {var xhr; if (XHR. XMLHttpRequest) {xhr = new XMLHttpRequest (); }else{xhr = new ActiveXObject (' microsoft.xmlhttp '); } xhr.open (' POST ', ' serverjson.php '); Note here that the key=value equals number on both sides do not appear blank, error will appear var data= ' name= ' +oaddname.value + ' &number= ' +oaddnumber.value + ' &s ex= ' +oaddsex.value + ' &job= ' +oaddjob.value; Set the Content-type xhr.setrequestheader between open and send (' Content-type ', ' application/x-www-form-urlencoded '); Xhr.send (data); Xhr.onreadystatechange=function () {if (xhr.readystate==4) {if (xhr.status=200) {var data=json.par SE (Xhr.responsetext); if (data.success) {oaddresult.innerhtml=data.msg; }else{oaddresult.innerhtml= ' ERROR: ' +data.msg; }}else{alert (' An error has occurred! ' +xhr.status}}}}
serverjson.php
<?php//Settings page content is HTML encoding format is 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");//defines a multidimensional array that contains information about the employee, each employee information is an array $staff = Array (array ("Name" = "Hong Qi", "number" = "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" =&G T "Product Manager");//Determine 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 page if ($_server[" request_method "] = =" GET ") {search ();} elseif ($_server[" request_method "] = =" POST ") {Create ();} Search employee by Employee ID () {//Check if there is a parameter for employee number//isset The test variable is set; empty determines whether the value is NULL//Hyper global variable $_get and $_post are used to collect form data if (!isset ( $_get["number"]) | | Empty($_get["number"])) {echo ' {"Success": false, "MSG": "Parameter Error"} '; Return The variables declared outside the}//function have Global scope and can only be accessed outside of the function. Global keywords are used to access globals $staff within functions; Gets the number parameter $number = $_get["number"]; $result = ' {' success ': false, ' msg ': ' No employee found. "}'; Traverse the $staff multidimensional array to find out if the employee whose key value is number is present, and if so, modify the returned result 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;} Create an employee function create () {//To determine if the information is 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")) {echo ' {"Success": false, "MSG": "Parameter error, employee information not complete"} "; Return //todo: Get post form data and save to database//prompt to save successfully echo ' {' success ': true, ' msg ': ' Employee: '. $_post["Name"]. ' Information saved successfully! "}';}? >
Summarize
The whole process is probably