Published: 21 Jun 2021 › Updated: 21 Jun 2021
AJAX开发笔记
- 下载与资源:
- 特点
- 前端往后端发送请求的四种方式:
- js格式转换
- python格式转换
- JS实现AJAX(原生方法)
- ajax发送get(jQuery)
- ajax发送post(jQuery)
- 快捷方法(jQuery)
- axios
下载与资源
特点
异步 JavaScript 和 XML,是指一种创建交互式网页应用的网页开发技术,可以异步刷新局部页面。
进一步封装的库有jQuery和axios,使得异步交互更简洁方便。
前端往后端发送请求的四种方式:
- 直接在地址栏中输入url
- a标签
- form表单
- 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
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:
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
- Nextjs初体验,和Nuxt的异同
- DeepTutor:AI个性化辅导平台 / ai #57
- ComfyUI:可编程和自动化的PS / ai #56
- 将Neo4j封装进Agent / ai #55
- 闲鱼省钱大法:极限0.5折!
- 对Neo4j批量导入结构化数据 / ai #54
- langchain对neo4j进行交互,写入和查询数据 / ai #53
- 知识图谱和图数据库Neo4j的作用和使用场景 / ai #52
- SpaceX、美股和比特币
- 又是币圈血洗日!
- 链股合流,当币安也开始卖股票啰
- 天涯社区重启,爷青回?
- 诺基亚在AI时代重新杀回来啦
- 《2049:未来10000天的可能》书中的镜像世界为什么不叫元宇宙
- 今天适合吃披萨
- 开通即被封,别再给Claude送人头了!
- 两根内存条引发的“官司”
- AI·Joe V12更新, 更新GPT-5.5和DeepSeek V4 等
- 中医进校园活动反响热烈
- 猪价低伤农,猪价贵伤民