Example of data interaction method between javascript front end and background

  • 2021-08-06 19:52:12
  • OfStack

In the development encountered in the absence of jQuery need to interact with the background part of the data, find part of the data using JavaScript to achieve the operation, record 1.


// Get XMLHttpRequest Object is used to interact with data in the background 

function getXHR(){
      var xmlHttp;
      try {
        xmlHttp=new XMLHttpRequest();// New version browser 
      }catch(e)
      {
        try{
          xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
          try{
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");// Old version browser           }
          catch(e)
          {
            alert(" Your browser does not support ajax");
            return false;
          }
        }
      }
      return xmlHttp;
    }

function check() {
      var pass = document.getElementById("pass").value;
 
      //1/ Get xhr Object 
      var xhr=getXHR();
      //2. Register status change listener 
      xhr.onreadystatechange=function(){
        if(xhr.readyState==4) {
          if(xhr.status==200) {
            var obj = document.getElementById("checkPass");
            if("true" == xhr.responseText){
              obj.innerHTML = " Verify through ";
              obj.style.color = "green";
			}else{
              obj.innerHTML = " The original password was entered incorrectly! ";
              obj.style.color = "brown";
              return;
			}
          }
        }
      }
      //3. Establish a connection to the server ( post Request mode, you can also use get Request method) 
      xhr.open("post"," The address of the requested data ");
      xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
      //4. Make a request to the server ( Use post Send data to the backstage by request )
      xhr.send("pass="+pass);
    }

Related articles: