一、原生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. Jenkins Git安装设置

    Jenkins Git安装设置 在此安装中,必须确保Internet连接可连接其安装 Jenkins 机器.在 Jenkins 仪表盘(主屏幕)的左侧单击 Manage Jenkins 选项.打开网址 ...

  2. Windows10 Oracle ODBC安装配置

    项目紧迫,需在短时间内交付成果,新团队成员,吐嘈之前数据库设计太low,很难看懂数据库表结构间的关系,为了使新同事更好的了解数据库表结构,特意使用powerDesigner对oracle.mysql数 ...

  3. python程序设计——面向对象程序设计:属性

    python 3.x 的属性 可以将属性设置为 可读,可修改,可删除 # 只读属性,不允许修改和删除 class Test: def __init__(self,value): self.__valu ...

  4. Teaching Machines to Understand Us 让机器理解我们 之三 自然语言学习及深度学习的信仰

    Language learning 自然语言学习 Facebook’s New York office is a three-minute stroll up Broadway from LeCun’ ...

  5. Thymeleaf教程【转】

    作者:不做浮躁的人 转自:http://www.blogjava.net/bjwulin/archive/2013/02/07/395234.html PS:其他推荐教程地址 http://blog. ...

  6. pat甲级1002

    1002. A+B for Polynomials (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue T ...

  7. pspo过程文档

    项目计划总结:       日期/任务      听课        编写程序         阅读相关书籍 日总计          周一      110          60         ...

  8. Android开发第二阶段(5)

    今天:对图片的替换修改,使整个app的图案化更美观. 明天:对Android的对sdcard的操作学习

  9. Java单例模式&static成员变量 区别

    当需要共享的变量很多时,使用static变量占用内存的时间过长,在类的整个生命周期. 而对象只是存在于对象的整个生命周期.   //饿汉式 class Single//类一加载,对象就已经存在了. { ...

  10. c 用指针操作结构体数组

    重点:指针自加,指向下一个结构体数组单元 #include <stdio.h> #include <stdlib.h> #include <string.h> #d ...