AJAX开发笔记

in hive-180932 •  3 years ago 

ajax

下载与资源

手册 |
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)
})
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!