一、原生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. Python环境搭建和pycharm安装

    Python环境搭建和pycharm安装 本人安装环境为Windows10系统,下载的Python版本为3.4社区版本,可参考 1.下载Python3.4版本 官网:https://www.pytho ...

  2. javascript 强制转换规则 boolean 布尔值类型

    摘自 <你不知道的Javascript(中卷)> p55 一句话简述, 假值表以外的值均可以认为是真值,部分浏览器可能自定义了假值表以外的假值,并不符合W3C规范,需要特殊对待. 首先也是 ...

  3. Tensorflow - Implement for a Softmax Regression Model on MNIST.

    Coding according to TensorFlow 官方文档中文版 import tensorflow as tf from tensorflow.examples.tutorials.mn ...

  4. java-HttpGetPost-图片字节流上传

    在java程序开发中经常用到与服务端的交互工作,主要的就是传递相应的参数请求从而获取到对应的结果加以处理 可以使用Get请求与Post请求,注意!这里的Get请求不是通过浏览器界面而是在程序代码中设置 ...

  5. 《Linux内核分析》学习总结与学习心得

    一.目录列表 第一周:计算机是如何工作的? http://www.cnblogs.com/dvew/p/5224866.html 第二周:操作系统是如何工作的? http://www.cnblogs. ...

  6. struts常量<constant>说明

    1.<constant name="struts.action.extension" value="do" />这个时候访问action都必须加.d ...

  7. Saver 保存与读取

    tensorflow 框架下的Saver 功能,用以保存和读取运算数据 Saver 保存数据 代码 import tensorflow as tf # Save to file #remember t ...

  8. 软工实践-Alpha 冲刺 (4/10)

    队名:起床一起肝活队 组长博客:博客链接 作业博客:班级博客本次作业的链接 组员情况 组员1(队长):白晨曦 过去两天完成了哪些任务 描述: 很胖,刚学,照猫画虎做了登录与注册界面. 展示GitHub ...

  9. ZOJ 1842 Prime Distance(素数筛选法2次使用)

    Prime Distance Time Limit: 2 Seconds      Memory Limit: 65536 KB The branch of mathematics called nu ...

  10. 青岛 2016ICPC 区域现场赛题目

    A. Relic Discovery B. Pocket Cube C. Pocky D. Lucky Coins E. Fibonacci F. Lambda Calculus G. Coding ...