框架----Django之Ajax全套实例(原生AJAX,jQuery Ajax,“伪”AJAX,JSONP,CORS)
一、原生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)的更多相关文章
- thinkphp中ajax使用实例(thinkphp内置支持ajax)
thinkphp中ajax使用实例(thinkphp内置支持ajax) 一.总结 1.thinkphp应该是内置支持ajax的,所以请求类型里面才会有是否是ajax // 是否为 Ajax 请求 if ...
- 利用python web框架django实现py-faster-rcnn demo实例
操作系统.编程环境及其他: window7 cpu python2.7 pycharm5.0 django1.8x 说明:本blog是上一篇blog(http://www.cnblogs.co ...
- Ajax简单实例(基于jQuery)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- ajax常用实例代码总结新手向参考(一)
http的交互方法有四种:get.post.put(增加数据).delete(删除数据) put和delete实现用的是get和post get方式 页面不能被修改,只是获取查询信息.但是提交的数 ...
- 伪ajax上传文件
伪ajax上传文件 最近在折腾伪ajax异步上传文件. 网上搜索了一下,发现大部分方法的input file控件都局限于form中,如果是在form外的呢? 必须动态生成一个临时form和临时if ...
- 伪ajax操作
什么是伪Ajax操作? 说白了就是假的ajax操作,但是它和正常的ajax操作的目的是一样的,把前端的信息发送到后台 先看一下代码吧! ajax.html <form action=" ...
- Django(十九)Ajax全套
参考博客:http://www.cnblogs.com/wupeiqi/articles/5703697.html 提交: - Form - Ajax 一.Ajax,偷偷向后台发请求 - XMLHtt ...
- python_way day21 Django文件上传Form方式提交,原生Ajax提交字符处啊,Django文件上传之原生Ajax方式、jQuery Ajax方式、iframe方式,Django验证码,抽屉示例,
python_way day21 1.Django文件上传至Form方式 2.原生Ajax文件上传提交表单 使用原生Ajax好处:不依赖jquery,在发送一个很小的文件或者字符串的时候就可以用原生A ...
- Python 20 Ajax全套
概述 对于web应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上. 1.传统的Web应用 一个简单操作需要 ...
随机推荐
- 05-Docker架构详解
Docker 的核心组件包括: Docker 客户端 - Client Docker 服务器 - Docker daemon Docker 镜像 - Image Registry Docker 容器 ...
- 小白初识 - 计数排序(CountingSort)
计数排序,属于桶排序特殊的一种. 当要排序n个数据的时候,如果所处的范围不大,我们可以取其中的最大值K,并将数据分散在K个桶里面, 每个桶里面的数据都是相同的(这样省去了桶内排序的时间),然后顺序取出 ...
- C# ArcFace 免费人脸识别 2.0 demo
**配置过程:** 1. 到[虹软官网](https://ai.arcsoft.com.cn/index.htm?utm_source=csdn&utm_medium=referral)下载S ...
- Python3 函数式编程自带函数
一 map函数 引子 需求1:num1=[1,2,3,4],我的需求是把num1中的每个元素平方后组成新列表. ret = [] num1 = [1,2,3,4] for i in num1: ret ...
- 作业要求20181113-4 Beta阶段第1周/共2周 Scrum立会报告+燃尽图 02
作业要求:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2384 版本控制:[https://git.coding.net/lglr201 ...
- 让程序运行更加面向用户——电梯V2.1
电梯V2.1 GitHub仓库地址 Problem 为程序添加命令行参数(自行利用搜索引擎进行学习). 写成 .cpp .h 文件分离的形式(大多数同学已经达到). 继续完善函数分离.模块化思想. 要 ...
- Alpha 冲刺(10/10)
队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 测试整体软件 展示GitHub当 ...
- Access连接数据源配置(新手必知)
今天要连接Access时发现win7 64位旗舰版控制面板中管理工具下的数据源(ODBC)配置竟然只有SQLServer的驱动,其他的都没有了,这可不好玩!上网百度了一番,有人也遇过这样的问题,我在此 ...
- 元素相加交换另解&puts的一个用法
#include<iostream> using namespace std; int main(){ int a,b; cin>>a>>b; a^=b; b^=a ...
- IT小小鸟阅读笔记
人生就像是一艘漂泊的船,你努力滑行了就会找到成功的彼岸,否则就漂泊一生.在这个物欲横流的时代有太多的诱惑使我们静不下心来,但是我们应该时时刻刻警醒自己要做一些对自己成长有意义的事,程序员虽然幸苦但是作 ...