A simple example of implementing Ajax with JS and JSON

Time:2019-10-27

preparation in advance

1. Install wampserver or other similar software to build the local integrated installation environment. I installed phpstudy.
2. HTML, JS, CSS and other files need to be placed in the WWW directory of PHP study, and the index page runs by default.
3、bootstrap.css

Screenshot of interface:

Phpstudy is very convenient to use. If your computer has not installed PHP, you should first configure the system environment variable, add the path of php.exe (found in the installation directory of phpstudy), and then enter php-v in CMD. If the installation version of PHP appears, the installation is successful.

Then create a new project under the WWW folder of phpstudy, here I call it ajaxdemo.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>index</title>
  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <style>
    .container{ width: 50%; margin-top: 30px; }
    .text-danger{ margin-top: 6px; }
  </style>
</head>
<body>
  <div>
    <div>
      <div>
        < div > employee query < / div >
      </div>
      <div>
        <div>
          <div>
            < label > employee No.: < label >
            <div>
              <input type="text">              
            </div>
            <div>
              < button > query < / button >
            </div>
          </div>
          <div>
            < label > query result: < label >
            <p></p>
          </div>
        </div>        
      </div>
    </div>
  </div>
  <div>
    <div>
      <div>
        < div > increase of employees < / div >
      </div>
      <div>
        <div>
          <div>
            < label > employee No.: < label >
            <div>
              <input type="text">
            </div>
          </div>
          <div>
            < label > employee name: < label >
            <div>
              <input type="text">
            </div>
          </div>
          <div>
            < label > employee gender: < label >
            <div>
              <input type="text">
            </div>
          </div>
          <div>
            < label > employee position: < label >
            <div>
              <input type="text">
            </div>
          </div>
          <div>
            <div>              
              < button > add employees < / button >
            </div>
          </div>
          <div>
            < label > results: < label >
            <p></p>
          </div>
        </div>        
      </div>
    </div>
  </div>
  <script src="staffManage.js"></script>
</body>
</html>

staffManage.js

The instantiation of Ajax can be divided into five points, which are easy to remember:

1. New an XMLHttpRequest instance
Pay attention to compatibility 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 three parameters. The first parameter specifies whether to get or post, the second parameter specifies the URL address, and the third parameter specifies whether to use asynchronous. The default value is true, so it is unnecessary to write.

3 * if it is a post request, 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 need parameters. The post request needs to pass in the body part as a string or a 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 '); // the feedback result shows

    //Query employee button click event  
    oSearchBtn.onclick=function(){
      searchStaff();
    }
    //Create query employee method
    function searchStaff(){
      //var xhr=new XMLHttpRequest();
      //The standard writing method and IE writing method are mixed together, which can be compatible with the lower 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 creating the XMLHttpRequest object, set the callback function of onreadystatechange. In the callback function, we usually only need to judge whether the request is completed through readyState = = = 4, and then judge whether it is a successful response according to status = = = 200.
      xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
          if(xhr.status=200){
            Var data = JSON. Parse (XHR. ResponseText); // JSON parsing method JSON. Parse or Eval ('(' + XHR. ResponseText + ')')
            oSearchRes.innerHTML=data.msg;
          }
        }
      }
    }

    //Add employees    
    Var oaddnumber = document. Getelementbyid ('add number '), // employee number
      Oaddname = document.getelementbyid ('add name '), // employee name
      Oaddsex = document. Getelementbyid ('add sex '), // employee gender
      Oaddjob = document. Getelementbyid ('add job '), // employee position
      Oaddsearch = document. Getelementbyid ('add search '), // add employee button
      Oaddresult = document. Getelementbyid ('add resultshow '); // the feedback result is displayed.

    //Add employees按钮点击事件
    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 that there is no space between the equals sign of key = value, and an error will occur.
      var data='name='+oAddname.value
      +'&number='+oAddnumber.value
      +'&sex='+oAddsex.value
      +'&job='+oAddjob.value;

      //Set content type between open and send
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

      xhr.send(data);

      xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
          if(xhr.status=200){
            var data=JSON.parse(xhr.responseText);
            if(data.success){
              oAddResult.innerHTML=data.msg;              
            }else{
              Oaddresult. InnerHTML = 'error occurred:' + data. MSG;
            }
          }else{
            Alert ('error occurred! '+ XHR. Status)
          }
        }
      }
    }

serverjson.php

<?php
//Set the content of the page as HTML and the encoding format as UTF-8
header("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");

//Define a multidimensional array containing employee information. Each employee information is an array.
$staff = array
  (
    Array ("name" = > Hong Qi "," number "= > 101", "sex" = > male "," job "= > General Manager"),
    Array ("name" = > Guo Jing "," number "= > 102", "sex" = > male "," job "= > Development Engineer"),
    Array ("name" = > Huang Rong "," number "= > 103", "sex" = > female "," job "= > Product Manager")
  );

//Judge if it is a get request, search; if it is a post request, create a new one.
//$_serveris a super global variable that can be used in all scopes of a script without using the global keyword.
//$_server ["request_method"] returns the request method used to access the page
if ($_SERVER["REQUEST_METHOD"] == "GET") {
  search();
} elseif ($_SERVER["REQUEST_METHOD"] == "POST"){
  create();
}

//Search employees by employee number
function search(){
  //Check if there is an employee number parameter
  //Isset detects whether the variable is set; empty determines whether the value is empty.
  //Super global variables $_getand $_postare used to collect form data
  if (!isset($_GET["number"]) || empty($_GET["number"])) {
    Echo '{"success": false, "MSG": "parameter error"}';
    return;
  }
  //Variables declared outside functions have global scope and can only be accessed outside functions.
  //The global keyword is used to access global variables within a function
  global $staff;
  //Get number parameter
  $number = $_GET["number"];
  $result = '{"success": false, "MSG": "employee not found. ">";

  //Traverse the $staff multidimensional array to find whether the employee with key number exists. If so, modify the returned result.
  foreach ($staff as $value) {
    if ($value["number"] == $number) {
      $result = '{"success": true, "MSG": "found employee: employee number:'. $value [" number "]. 
              'employee name:'. $value ["name"]. 
              'employee gender:'. $value ["sex"]. 
              'employee position:'. $value ["job"]. '"}';
      break;
    }
  }
  echo $result;
}

//Create employee
function create(){
  //Judge whether 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": "wrong parameter, incomplete employee information"}';
    return;
  }
  //Todo: get post form data and save it to the database

  //Prompt: save successfully
  Echo '{"success": true, "MSG": "Employee:'. $ ">";
}

?>

summary

The whole process is as follows:

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

The method of obtaining the resolution of display by pyqt5

The code is as follows import sys from PyQt5.QtWidgets import QApplication, QWidget class Example(QWidget): def __init__(self): super().__init__() self.initUI() #Interface drawing to initui method def initUI(self): self.desktop = QApplication.desktop() #Get display resolution size self.screenRect = self.desktop.screenGeometry() self.height = self.screenRect.height() self.width = self.screenRect.width() print(self.height) print(self.width) #Show window self.show() if __name__ == ‘__main__’: #Create applications and objects app […]