一、原生AJAX,jQuery Ajax,“伪”AJAX,JSONP

1. 浏览器访问

http://127.0.0.1:8000/index/

http://127.0.0.1:8000/fake_ajax/

http://127.0.0.1:8000/index/jsonp/

http://127.0.0.1:8000/autohome/

2. urls

from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^add1/', views.add1),
url(r'^add2/', views.add2),
url(r'^autohome/', views.autohome),
url(r'^fake_ajax/', views.fake_ajax),
url(r'^jsonp/', views.jsonp),
]

3. views

 from django.shortcuts import render,HttpResponse,redirect

 def index(request):
return render(request,'index.html') def add1(request):
a1 = int(request.POST.get('i1'))
a2 = int(request.POST.get('i2'))
return HttpResponse(a1 + a2) def add2(request):
if request.method == 'GET':
i1 = int(request.GET.get('i1'))
i2 = int(request.GET.get('i2'))
print('add2....')
return HttpResponse(i1 + i2)
else:
print(request.POST)
print(request.body)
return HttpResponse('...') def autohome(request):
return render(request,'autohome.html') def fake_ajax(request):
if request.method == 'GET':
return render(request,'fake_ajax.html')
else:
print(request.POST)
return HttpResponse('返回值') def jsonp(request):
return render(request,'jsonp.html')

views

4. templates

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>首页</h1>
<input type="text" id="i1" />
+
<input type="text" id="i2" />
=
<input type="text" id="i3" /> <input type="button" id="btn1" value="jQuery Ajax" onclick="add1();" />
<input type="button" id="btn2" value="原生Ajax" onclick="add2();" /> <script src="/static/jquery-3.2.1.js"></script>
<script>
/* $$$$$$$ jQuery Ajax $$$$$$$ */
function add1() {
$.ajax({
url:'/add1/',
type:'POST',
data:{'i1':$('#i1').val(),'i2':$('#i2').val()},
success:function (arg) {
$('#i3').val(arg);
}
}) } /* $$$$$$$ 原生Ajax $$$$$$$ */
function add2() {
/* $$$$$$$ GET方式 $$$$$$$ */
/* var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
alert(xhr.responseText);
}
};
xhr.open('GET','/add2/?i1=12&i2=19');
xhr.send(); */ /* $$$$$$$ POST方式 $$$$$$$ */
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
alert(xhr.responseText);
}
};
xhr.open('POST','/add2/');
xhr.setRequestHeader('Content-Typr','application/x-www-form-urlencoded');
xhr.send('i1=12&i2=19');
}
</script>
</body>
</html>

index.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<input type="text" id="txt1" />
<input type="button" value="查看" onclick="changeScr();" />
</div>
<iframe id="ifr" style="width: 1200px;height: 1000px;" src="http://www.autohome.com.cn"></iframe> <script>
function changeScr() {
var inp = document.getElementById('txt1').value;
document.getElementById('ifr').src = inp;
}
</script>
</body>
</html>

autohome.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="f1" method="POST" action="/fake_ajax/" target="ifr">
<iframe id="ifr" name="ifr" style="display: none;"></iframe>
<input type="text" name="user" />
<a onclick="submitForm();">提交</a>
</form> <script>
function submitForm() {
document.getElementById('ifr').onload = loadIframe;
document.getElementById('f1').submit();
}
function loadIframe() {
var content = document.getElementById('ifr').contentWindow.document.body.innerText;
alert(content);
}
</script>
</body>
</html>

fake_ajax.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="/static/commons.js"></script>
</head>
<body>
<a onclick="sendMsg();">发送</a>
<script>
function sendMsg() {
var tag = document.createElement('scaript');
tag.src = "http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403";
document.head.appendChild(tag);
}
</script>
</body>
</html>

jsonp.html

5. static

 function list(arg){
console.log(arg);
}

commons

 f1(123)

commons2

二、CORS

cors 跨站资源共享

#响应头加入
obj["Access-Control-Allow-Origin"] = "http://www.s4.com:8000" #仅这个域名可以访问
obj["Access-Control-Allow-Origin"] = "*" #所有域名都可以访问

a. www.s4.com 访问 www.s5.com,在响应头加入数据,同源策略就不生效 

1. www.s4.com

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cors/', views.cors),
]

urls.py

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 def cors(request):
return render(request,"core.html") view.py

view.py

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <input type="button" value="获取用户列表" onclick="getUsers()"> <ul id="user_list"></ul> <script src="/static/jquery-3.2.1.js"></script> <script>
function getUsers() {
$.ajax({
url:"http://www.s5.com:9000/user/",
type:"GET",
success:function (arg) {
console.log(arg);
console.log(typeof arg);
for (var i = 0; i < arg.length; i++) {
var tag = document.createElement("li");
tag.innerText = arg[i];
document.getElementById("user_list").appendChild(tag);
}
}
})
}
</script> </body>
</html> core.html

core.html

2. www.s5.com

urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^user', views.user),
]

urls.py

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 import json
def user(request): user_list = ["alex","egon","root"]
user_list_str = json.dumps(user_list) obj = HttpResponse(user_list_str) obj["Access-Control-Allow-Origin"] = "http://www.s4.com:8000"
return obj views.py

views.py

b.预检request.method == "OPTIONS

1. www.s4.com

urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^cors/', views.cors),
]

urls.py

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 def cors(request):
return render(request,"core.html") views.py

views.py

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <input type="button" value="获取用户列表" onclick="getUsers()"> <ul id="user_list"></ul> <script src="/static/jquery-3.2.1.js"></script> <script>
function getUsers() {
$.ajax({
url:"http://www.s5.com:9000/user/",
type:"DELETE",
success:function (arg) {
console.log(arg); }
})
}
</script> </body>
</html> core.html

core.html

2. www.s5.com

urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^user', views.user),
]

urls

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 import json
def user(request):
print(request.method)
if request.method == "OPTIONS": obj = HttpResponse()
obj["Access-Control-Allow-Origin"] = "*"
obj["Access-Control-Allow-Methods"] = "DELETE"
return obj obj = HttpResponse("..")
obj["Access-Control-Allow-Origin"] = "*"
return obj view.py

views.py

框架----Django之Ajax全套实例(原生AJAX,jQuery Ajax,“伪”AJAX,JSONP,CORS)的更多相关文章

  1. thinkphp中ajax使用实例(thinkphp内置支持ajax)

    thinkphp中ajax使用实例(thinkphp内置支持ajax) 一.总结 1.thinkphp应该是内置支持ajax的,所以请求类型里面才会有是否是ajax // 是否为 Ajax 请求 if ...

  2. 利用python web框架django实现py-faster-rcnn demo实例

    操作系统.编程环境及其他: window7  cpu  python2.7  pycharm5.0  django1.8x 说明:本blog是上一篇blog(http://www.cnblogs.co ...

  3. Ajax简单实例(基于jQuery)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  4. ajax常用实例代码总结新手向参考(一)

    http的交互方法有四种:get.post.put(增加数据).delete(删除数据) put和delete实现用的是get和post   get方式 页面不能被修改,只是获取查询信息.但是提交的数 ...

  5. 伪ajax上传文件

    伪ajax上传文件   最近在折腾伪ajax异步上传文件. 网上搜索了一下,发现大部分方法的input file控件都局限于form中,如果是在form外的呢? 必须动态生成一个临时form和临时if ...

  6. 伪ajax操作

    什么是伪Ajax操作? 说白了就是假的ajax操作,但是它和正常的ajax操作的目的是一样的,把前端的信息发送到后台 先看一下代码吧! ajax.html <form action=" ...

  7. Django(十九)Ajax全套

    参考博客:http://www.cnblogs.com/wupeiqi/articles/5703697.html 提交: - Form - Ajax 一.Ajax,偷偷向后台发请求 - XMLHtt ...

  8. python_way day21 Django文件上传Form方式提交,原生Ajax提交字符处啊,Django文件上传之原生Ajax方式、jQuery Ajax方式、iframe方式,Django验证码,抽屉示例,

    python_way day21 1.Django文件上传至Form方式 2.原生Ajax文件上传提交表单 使用原生Ajax好处:不依赖jquery,在发送一个很小的文件或者字符串的时候就可以用原生A ...

  9. Python 20 Ajax全套

    概述 对于web应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上. 1.传统的Web应用 一个简单操作需要 ...

随机推荐

  1. WebGL树形结构的模型渲染流程

    今天和大家分享的是webgl渲染树形结构的流程.用过threejs,babylonjs的同学都知道,一个大模型都是由n个子模型拼装而成的,那么如何依次渲染子模型,以及渲染每个子模型在原生webgl中的 ...

  2. MongoDB 极简实践入门

    原作者StevenSLXie; 原链接(https://github.com/StevenSLXie/Tutorials-for-Web-Developers/blob/master/MongoDB% ...

  3. 数据库sql优化总结之1-百万级数据库优化方案+案例分析

    项目背景 有三张百万级数据表 知识点表(ex_subject_point)9,316条数据 试题表(ex_question_junior)2,159,519条数据 有45个字段 知识点试题关系表(ex ...

  4. 用Python爬下今日头条所有美女,美滋滋!

      我们的学习爬虫的动力是什么? 有人可能会说:如果我学好了,我可以找一个高薪的工作. 有人可能会说:我学习编程希望能够为社会做贡献(手动滑稽) 有人可能会说:为了妹子! ..... 其实我们会发现妹 ...

  5. Windows下遍历某目录下的文件

    需求:要求遍历某个目录下的所有文件,文件夹 之前遇到过一些参考程序,其中有一种方法只能遍历 FAT32 格式的目录, 无法遍历NTFS的目录.

  6. Halcon如何保存仿射变换矩阵

    这里我们通过序列化来实现的,如下图,写到硬盘的HomMat2D_1内容和从硬盘里HomMat2D_2读出的内容一致,源代码在图片下方. Halcon源代码: hom_mat2d_identity (H ...

  7. leetcode个人题解——#43 Multiply Strings

    思路:高精度乘法就可以了. 有两个错误以前没在意,1.成员属性定义时候不能进行初始化, vector<); 这样隐性调用了函数进行初始化的形式特别要注意,也是错误的: 2.容器类只有分配了空间时 ...

  8. Python Requests库简单入门

    我对Python网络爬虫的学习主要是基于中国慕课网上嵩天老师的讲授,写博客的目的是为了更好触类旁通,并且作为学习笔记之后复习回顾. 1.引言 requests 库是一个简洁且简单的处理HTTP请求的第 ...

  9. JDK源码分析 – HashMap

    HashMap类的申明 HashMap的定义如下: public class HashMap<K,V> extends AbstractMap<K,V> implements ...

  10. Beta 阶段项目计划

    Beta 阶段项目计划 NewTeam 目标 实现用户数量的目标. 在多个平台发布 完成稳定运行.界面优雅的客户端 充分测试,避免发布后出现bug影响用户使用 及时更新开发文档 合理安排时间,避免和其 ...