WEB--Ajax basics

Introduction to Ajax

  • Ajax definition: Asynchronous JavaScript and XML, which means to use JavaScript to execute asynchronous network requests, is a technology that can update part of the web page without reloading the entire web page
  • Ajax function: To allow the user to stay on the current page and make a new HTTP request at the same time, the new request must be sent with JavaScript. After receiving the data, the page is updated with JavaScript, so that the user feels that he is still staying in the current page. Page, but the data can be constantly updated
  • Ajax principle: an event occurs in the browser first, such as a click. At this time, js creates an XMLHttpRequest object and sends a request. The server processes the request and returns data. At this time, the js process returns and updates the page.
  • Reference document: https://www.cnblogs.com/nuannuan7362/p/6441192.html?utm_source=itdadao&utm_medium=referral

Ajax request steps

  1. Initialize/create an XMLHttpRequest asynchronous object
var xmlhttp;
xmlhttp =new XMLHttpRequest();     //初始化,创建对象
  1. Set callback function
xmlhttp.onreadystatechange=callback; //响应回掉/监听
  1. Use the open() method to establish a connection with the server
// get
xmlhttp.open("GET",url,true);   

// post
xmlhttp.open("POST",url,true);   
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")   // 设置请求头
  1. Send the request using the send() method
xmlhttp.send('null');  // get请求发送
xmlhttp.send({
    
    'user': user, 'pwd': pwd});  //post请求发送
  1. Receive the returned data
function callback() {
    
    
  // 判断异步对象的状态
  if(xmlhttp.readyState == 4) {
    
    
    // 判断交互是否成功
    if(xmlhttp.status == 200) {
    
    
      // 获取服务器响应的数据
      var res = xmlhttp.responseText
      // 解析数据
      res = JSON.parse(res)
    }
  }
}

XMLHttpRequest

  • There are five possible values ​​for xmlhttp.readyState:
  • 0 (Uninitialized): The (XMLHttpRequest) object has been created, but the open() method has not been called.
  • 1 (Load): The open() method has been called, but the request has not been sent yet.
  • 2 (Load complete): The request has been sent.
  • 3 (Interactive): Partial response data can be received.
  • 4 (Completed): All data has been received and the connection has been closed.
  • xmlhttp.status: same as http/https request return status
  • 200: Successful response

Landing case (xhr)

  • Description: A page with a user name, password and login button. After clicking the login button through ajax, it is judged whether the login is successful, and the page does not refresh
<!--ajax.html-->
   <h1>一、表单发送ajax请求登录</h1>
   <label for="username">用户名</label>
   <input type="text" name="username" id="username">
   <label for="password">密码</label>
   <input type="password" name="password" id="password">
   <input type="button" id="login" value="登录">
   <div></div>
// main.js

$(document).ready(function(){
    
    
    var xmlhttp;

    $('#login').click(function(){
    
    
        var user = document.getElementById("username").value;
        var pwd = document.getElementById("password").value;
        var url = "http://127.0.0.1:8000/login"

        xmlhttp =new XMLHttpRequest();     //初始化,创建对象
        xmlhttp.onreadystatechange=callback; //响应回掉/监听
        xmlhttp.open("POST",url,true);   //设置访问的页面
        
        // 组装post数据并发送请求
        var formData = new FormData();
        formData.append('user', user);
        formData.append('pwd', pwd);
        xmlhttp.send(formData);

    });

    // 监听函数
    function callback() {
    
    
        // 判断异步对象的状态
        if(xmlhttp.readyState == 4) {
    
    
          // 判断交互是否成功
          if(xmlhttp.status == 200) {
    
    
            // 获取服务器响应的数据
            var res = xmlhttp.responseText
            // 解析数据
            res = JSON.parse(res)
            if (res.code ===1) {
    
    
              alert('成功')
            }else{
    
    
              alert('失败')
          }
          }
        }
      }  
}); 
# server.py
from flask import Flask, render_template, request, jsonify


app =  Flask(__name__)


user_info = {
    
    'user': 'zhangsan', 'pwd': '123456'}


@app.route('/', methods=['get'])
def index():    
    return render_template('ajax.html')


@app.route('/login', methods=['post'])
def login():
    data = request.form
    if user_info.get('user') == data.get('user') and user_info.get('pwd') == data.get('pwd'):
        return jsonify({
    
    'code': 1, 'data':None, 'msg': '成功'})
    else:
        return jsonify({
    
    'code': 0, 'data':None, 'msg': '密码有误'})

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0',port=8000)

jquery ajax

  • Way one: success
//  main.js
$(function(){
    
    
    $('#login').click(function(){
    
    
        // 获取账号密码
        var user = $('#username').val();
        var pwd = $('#password').val();
        // 方式一 
        $.ajax({
    
    
            url: '/login',    // url=  host + api
            type: 'post',
            data: {
    
    'user': user, 'pwd': pwd},
            dataType: 'json',
            success: function(data){
    
    
                if (data.code === 1){
    
    
                    alert(data.msg);
                }else{
    
    
                    alert(data.msg);
                }  
            },
        })

    });
});

  • Method 2: done & fail
//  main.js

$(function(){
    
    
    $('#login').click(function(){
    
    
        // 获取账号密码
        var user = $('#username').val();
        var pwd = $('#password').val();

        // 方式二
        $.ajax({
    
    
            url: '/login',
            type: 'post',
            data: {
    
    'user': user, 'pwd': pwd},
            dataType: 'json'
        }).done(function(data){
    
    
            if (data.code === 1){
    
    
                alert(data.msg);
            }else{
    
    
                alert(data.msg);
            }
        }).fail(function(){
    
    
            alert('请求失败')
        })
    });
});

Cascading drop-down box (jQuery+Ajax)

  • Description: Realize the linkage display of the secondary drop-down box with the primary drop-down box
<!-- demo .html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax</title>
    <link rel="shortcut icon" href="../static/img/svg/favicon.ico">
    <script type="text/javascript" src="../static/js/jquery-1.12.4.min.js"></script>
    <script type="text/javascript" src="../static/js/main.js"></script>
</head>
<body>
    <form action="">
        <label for="pro">项目</label>
        <select name="pro" id="pro" style="width: 100px;">
            <option value="">请选择</option>
        </select>
        <label for="interface">接口</label>
        <select name="inter" id="interface" style="width: 100px;">
            <option value="">请选择</option>
        </select>
    </form>
</body>
</html>
// main.js

$(function(){
    
    
  var pro = $('#pro')
  $.ajax({
    
    
    url: '/pro_list',    
    type: 'get',
    data: '',
    dataType: 'json',
  }).done(function(data){
    
    
    if (data.code === 1){
    
    
      var res = data.data
      for (item in res){
    
    
        var option = '<option value=' + res[item].id + '>' + res[item].title + '</option>'
        pro.append(option);
      }
    }else{
    
    
      alert('请求失败')
    };
  });

  // 二级下拉框
  pro.change(function(){
    
    
    var pro_id = pro.val();
    $.ajax({
    
    
      url: '/interface',    
      type: 'post',
      data: {
    
    'pro_id': pro_id},
      dataType: 'json',
    }).done(function(data){
    
    
      var inter = $('#interface');
      if (data.code === 1){
    
    
        inter.empty();  // 清空二级下拉框上一次选择内容
        var res = data.data
        for (item in res){
    
    
          var option = '<option value=>' + res[item].name + '</option>'
          inter.append(option);
        }
      }else{
    
    
        alert('请求失败')
      };
    });
  })

});

Guess you like

Origin blog.csdn.net/qq_25672165/article/details/112915388