jquery를 사용하지 않는 Vanilla XMLHttpRequest 메서드

28533 단어

소개



Ajax는 "Asynchronous JavaScript and XML"의 줄임말로 클라이언트 측에서 다양한 웹 기술을 사용하여 기존 페이지의 표시 및 동작을 방해하지 않고 비동기식 웹 애플리케이션을 만드는 일련의 웹 개발 기술입니다.
Ajax는 부분 페이지 업데이트를 만드는 메커니즘입니다. 완전히 새로 고칠 필요 없이 서버에서 가져온 데이터로 페이지의 섹션을 업데이트할 수 있습니다. 이러한 방식으로 부분 업데이트를 수행하면 유동적인 사용자 경험을 만드는 데 효과적일 수 있으며 서버에 가해지는 부하를 줄일 수 있습니다.

기본 Ajax 요청 분석:



var xhr = new XMLHttpRequest();
xhr.open('POST', 'send-ajax-data.php');
xhr.onreadystate = function () {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; // status 200 is a successful return.
  if (xhr.readyState === DONE) {
    if (xhr.status === OK) {
      console.log(xhr.responseText); // 'This is the returned text.'
    } else {
      console.log('Error: ' + xhr.status); // An error occurred during the request.
    }
  }
};
xhr.send(null);

여기서는 서버에 HTTP 요청을 하기 위해 필요한 클래스의 변수를 해제합니다. 그런 다음 HTTP 요청 메서드를 첫 번째 매개 변수로 지정하고 요청하는 페이지의 URL을 두 번째로 지정하여 open 메서드를 호출합니다.onreadystate는 비동기식이므로 언제든지 호출됩니다. 이러한 유형의 함수는 일부 처리가 완료되면 호출되는 콜백입니다.
마지막으로 매개변수로 전달하는 send 메서드null를 호출합니다. 요청을 게시하는 경우 이 매개변수에는 요청과 함께 보내려는 모든 데이터가 포함되어야 합니다.
자세한 설명이 있습니다
코딩을 시작하고 바닐라 js의 결과와 아름다움을 봅시다
  • 로그인 양식 만들기

  • <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" csontent="width=device-width, initial-scale=1.0">
        <title>pratical login page</title>
        <link rel="stylesheet" href="fontawesome-free-5.15.4-web/css/all.css">
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
       <div class="wrapper">
            <section class="form login">
                <header>Login</header>
                <form action="#" method="POST" enctype="multipart/form-data" id="myForm">
                    <div class="error-txt"></div>
                        <div class="field input">
                            <label >Username</label>
                            <input type="text" name = "username" placeholder="Enter username">
                        </div>
                        <div class="field input">
                            <label >Password</label>
                            <input type="password" name ="password" placeholder="Enter your password">
                            <i class="fas fa-eye"></i>
                        </div>
                        <div class="field button">
                            <input type="submit" value="continue to chat" >
                    </div>
                </form>
                <div class="link">Not yet signup? <a href="index.php">Signup now</a></div>
            </section>
       </div>
       <script src="login.js"></script>
    

  • 필요한 경우 로그인 페이지 스타일 지정

  • css(계단식 스타일시트)를 추가하여 페이지를 구조화하고 아름답게 만들 수 있습니다.

    *{
        margin: 0 ;
        padding: 0 ;
        box-sizing: border-box;
        text-decoration: none;
        font-family: 'poppins',sans-serif;
    }
    body{ 
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: #f7f7f7;
    }
    .wrapper{
    background: rgb(172, 224, 87);
    width: 450px;
    border-radius: 16px;
    box-shadow: 0,0,128px,0 rgba(0, 0, 0, 0.1),
                0 32px 64px -48px rgba(0, 0,0,0.5);
    }
    /* signup form css code */
    .form{
        padding: 25px 30px;
    }
    .form header{
        font-size: 25px;
        font-weight: 600;
        padding-bottom: 10px;
        border-bottom: 1px solid #e6e6e6;
    }
    .form form{
        margin: 20px 0 ;
    }
    .form form .error-txt{
        color: #721c24;
        background: #f8d7da;
        padding: 8px 10px;
        text-align: center;
        border-radius: 5px;
        margin-bottom: 10px;
        border: 1px solid #f5c6cb;
        display: none;
    }
    .form form .field{
        position: relative;
        display: flex;
        flex-direction: column;
        margin-bottom: 10px;
    }
    
        .form form .name-details{
    display: flex;
    }
    form .name-details .field:first-child{
        margin-right: 10px;
    }
    form .name-details .field:last-child{
        margin-left: 10px;
    }
    .form form .field input{
        outline: none;
    }
    .form form .input input{
        height: 40px;
        width: 100%;
        font-size: 16px;
        padding: 0 10px;
        border: 1px solid #ccc;
    }
    .form form .image input{
        font-size: 17px;
    }
    .form form .button input{
        margin-top: 13px;
        height: 45px;
        border: none;
        font-size: 17px;
        font-weight: 400;
        background: #333;
        color: #fff;
        border-radius: 5px;
        cursor: pointer;
    }
    
    .form form .field i{
        position: absolute;
        right: 10px;
        color: #ccc;
        top: 58%;
        transform:(-50%);
        cursor: pointer;
    }
    .form form .field i.active::before{
        content: "\f070";
        color: #333;
    }
    .form .link{
        text-align: center;
        margin:10px 0;
        font-size: 17px;
    
    }
    .form .link a{
        color: #333;
    }
    .form .link a:hover{
        text-decoration: underline;
    }
    


  • 데이터베이스에 대한 연결 생성

  • <?php
    $conn = mysqli_connect("localhost","root","","a_database");
    if ($conn) {
    
    }else{
        echo "Not connected ";
    }
    ?>
    


  • 데이터베이스에 연결하는 php 파일 생성

  • <?php
    include "connection.php";
    
        $username =   $_POST['username'];
        $password =   $_POST['password'];
    
        if (! empty($username) && ! empty($password)){
    //lets check if user entered email and password matched database and table
          $sql = mysqli_query($conn, "SELECT * FROM users WHERE username = '$username' AND password = '$password '" );
          if (mysqli_num_rows($sql) > 0 ) {//check if user credential matched
           echo "success";
    
          }else {
            echo "Username and Password incorrect";
          }
        }else {
          echo "All field are required";
        }
    
    
    ?>
    


    위의 코드에서 우리는 연결 스크립트를 포함하고 페이지가 Else 문을 에코해야 하는 경우 사용자 이름과 암호가 올바른지 확인합니다.
  • 바닐라 javascript를 사용하여 데이터베이스에서 데이터 가져오기

  • const form = document.querySelector("#myForm"),
      errorText = form.querySelector(".error-txt");
    
    form.onsubmit = (e) => {
      e.preventDefault();//preventing form from submitting
      //start with ajax
    
      let xhr = new XMLHttpRequest();// creating xml object
      xhr.open("POST", "get.php", true);
      xhr.onload = () => {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.status === 200) {//status 200 is a successful return.
            let data = xhr.response;
    
            if (data == "success") {
    
              location.href = "logout.php";
    
            } else {
              errorText.textContent = data;
              errorText.style.display = "block";
    
            }
          } 
        }
      }
      // sending form from ajax to php
      let formData = new FormData(form); // creating new form object.
      xhr.send(formData);//sending the  form data to php
    
    }
    


    다음은 로그인 양식의 이미지입니다.



    양식 제출 후 출력


    결론



    이 기사에서는 사용자 이름과 암호를 수락한 다음 Vanilla Ajax를 사용하여 전체 페이지를 로드하지 않고 인증을 위해 백엔드(데이터베이스)로 보내는 간단한 로그인 페이지를 만들 수 있었습니다.
    바닐라 아약스의 벤치 프레스를 즐기셨기를 바랍니다. 사실 우리는 jQuery의 목발, 에헴 족쇄 없이 Ajax의 기본 사항 대부분을 다루었습니다.

    Ajax 호출을 만드는 간결한 방법을 알려드리겠습니다.

    좋은 웹페이지 즐겨찾기