lemooljiang avatar

AJAX开发笔记

lemooljiang

Published: 21 Jun 2021 › Updated: 21 Jun 2021AJAX开发笔记

AJAX开发笔记

ajax.jpg

下载与资源

手册 |
jquery手册 |
参考

特点

异步 JavaScript 和 XML,是指一种创建交互式网页应用的网页开发技术,可以异步刷新局部页面。

进一步封装的库有jQuery和axios,使得异步交互更简洁方便。

前端往后端发送请求的四种方式:

  1. 直接在地址栏中输入url
  2. a标签
  3. form表单
  4. AJAX

js格式转换

//JSON对象转成字符串
var obj = {'name':'xiaohei','age':18}
var obj_str = JSON.stringify(obj)

//字符串转成JSON对象
JSON.parse(obj_str)

python格式转换

# 将字符串反序列化成JSON对象
import json
s = '{"name":"xiaohei", "age":18}'
ret = json.loads(s)
print(s)

# 皎字典序列化成字符串
ret2 = json.dumps(ret)

JS实现AJAX(原生方法)

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "/ajax_test/", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("username=q1mi&password=123456");
xmlHttp.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
    alert(this.responseText);
    }
};

ajax发送get(jQuery)

<script src="js/jquery-3.4.1.js"></script>

$.ajax({
    url: "/test/",
    type: "GET",
    data: {"key": "value", "age":18},
    success: function (args) {
        $("#val3").val(args);
    }
})
})

ajax发送post(jQuery)

# 方法一:CSRFToken通过获取返回的cookie中的字符串 放置在请求头中发送。
jquery.cookie.js
$.ajax({
    url: "",
    type: "POST",
    headers: {"X-CSRFToken": $.cookie("csrftoken")},
    success: function (args) {
        $("#val3").val(args);
    }
})
})

# 方法二:setupajax.js,使用时导入即可。
$.ajax({
    url: "",
    type: "POST",
    success: function (args) {
        $("#val3").val(args);
    }
})
})

// setupajax.js
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
};
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});

快捷方法(jQuery)

$.get("test.cgi", { name: "John", time: "2pm" }, function(data){
     alert("Data Loaded: " + data);
   });

$.post("test.php", { name: "John", time: "2pm" }, function(data) {
    process(data);
  });

$.getJSON("test.js", function(json) {
   alert("JSON Data: " + json.users[3].name);
 });

axios

axios中文文档
参考
参考2

cnpm install axios --save

//main.js
import axios from 'axios'
Vue.prototype.axios = axios
//其它js中使用:
this.axios({......})
//或者是哪里使用哪里就导入:
import axios from 'axios'
axios.get(){}

Promise使this.

methods:{
  get(){    //尽量使用箭头函数,没有this的问题
    this.axios.get('http://vue.studyit.io/api/getlunbo').then(res => {
      console.log(res.data)
    }).catch(error => {
      console.log(error)
    })
  }
}

this.axios.request({
    method: 'post',
    url: 'http://192.168.1.101:8000/login/',
    data:{
      username:this.username,
      password:this.password
    }
  })
  .then( (arg) => {
      console.log(222,arg)  
      })
  .catch((error) => {
    console.log(333,error)
    })

this.axios.request({
  method:"get",
  url:'http://192.168.1.101:8000/authors/'
}).then( (arg) => {
  console.log(111,arg.data)
}).catch( (error) => {
  console.log(333,error)
})

Leave AJAX开发笔记 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #hive-105017 posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang