原生ajax发送请求
- 先创建一个 xmlhttprequest 对象
- 指定连接 xmr.open(method, url, true) 三个 参数 1 发送的方式 2 发送的目标地址 3 是否采用异步 默认的就是 true
- 发送数据 xmr.send(string) 发送的只能是字符串形式的 如果是对象的话 需要先 序列化成字符串 然后再发送
- 当使用的是post 发送的时候需要发送一个请求头:xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded; charset-UTF-8’);
- 根据状态之判断返回的内容
代码演示:
function getXHR(){
//兼容IE6 7 的写法
var xhr = null;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
//在 ie 6 7 中是没有xmlhttp的
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function Ajax1(){
var xhr = getXHR();
//var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax_json/',true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
// 接收完毕
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.setRequestHeader('k1','v1');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
xhr.send("name=root;pwd=123");
}
通过jquery 来发送ajax请求
一站式封装完成 代码演示:
最新的写法:
$(function() {
var data_json = ''
$('button').click(function() {
$.ajax({
url: '/login/json/',
type: 'POST',
dataType: 'json',
data: {
"name": 'value1',
"age": 30
}
.done(function(data) {
// 在指定了上面的datatypejson的时候 直接就给解析成json 格式的数据了
console.log(data.code);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
})
})
之前的写法
$(function() {
var data_json = ''
$('button').click(function() {
$.ajax({
url: '/login/json/',
type: 'POST',
dataType: 'json',
data: {
"name": 'value1',
"age": 30
},
// 回调函数 data 是返回的数据
success:function(data){
console.log(data);
}
python 后台数据的处理
后台返回 是一个querydic 字典 可以按照字典的形式 来解析请求发送来的数据
# ajax
def josn(request):
print(request.POST)
demo = request.POST.get('name')
age = request.POST.get('age')
print(demo)
print(age)
# for key, value in demo.items():
# print(demo[key])
# print(key, value)
ajax_dic = {'code': 200, "data": 'hello'}
return HttpResponse(json.dumps(ajax_dic))