打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
【Python之路】第十七篇
概述

1、传统的Web应用

一个简单操作需要重新加载全局数据

2、AJAX

AJAX,Asynchronous JavaScript and XML (异步的JavaScript和XML),一种创建交互式网页应用的网页开发技术方案。

  • 异步的JavaScript:
    使用 【JavaScript语言】 以及 相关【浏览器提供类库】 的功能向服务端发送请求,当服务端处理完请求之后,【自动执行某个JavaScript的回调函数】。
    PS:以上请求和响应的整个过程是【偷偷】进行的,页面上无任何感知。
  • XML
    XML是一种标记语言,是Ajax在和后台交互时传输数据的格式之一

利用AJAX可以做:
1、注册时,输入用户名自动检测用户是否已经存在。
2、登陆时,提示用户名密码错误
3、删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除。(博客园)

“伪”AJAX

由于HTML标签的iframe标签具有局部加载内容的特性,所以可以使用其来伪造Ajax请求。

iframe.src 重新加载,页面不刷新

<!DOCTYPE html><html>    <head lang="en">        <meta charset="UTF-8">        <title></title>    </head>    <body>        <div>            <p>请输入要加载的地址:<span id="currentTime"></span></p>            <p>                <input id="url" type="text" />                <input type="button" value="刷新" onclick="LoadPage();">            </p>        </div>          <div>            <h3>加载页面位置:</h3>            <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>        </div>          <script type="text/javascript">              window.onload= function(){                var myDate = new Date();                document.getElementById('currentTime').innerText = myDate.getTime();            };            function LoadPage(){                var targetUrl =  document.getElementById('url').value;                document.getElementById("iframePosition").src = targetUrl;            }        </script>    </body></html>

 

原生AJAX

Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。

1、XmlHttpRequest对象介绍

XmlHttpRequest对象的主要方法:

View Code

XmlHttpRequest对象的主要属性:

View Code

2、跨浏览器支持

  • XmlHttpRequest

    IE7+, Firefox, Chrome, Opera, etc.

  • ActiveXObject("Microsoft.XMLHTTP")

    IE6, IE5

基于原生Ajax-demo

原生ajax发送post请求要带上请求头

1
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
jQuery Ajax

jQuery其实就是一个JavaScript的类库,其将复杂的功能做了上层封装,使得开发者可以在其基础上写更少的代码实现更多的功能。

  • jQuery 不是生产者,而是大自然搬运工。
  • jQuery Ajax本质 XMLHttpRequest 或 ActiveXObject 

注:2.+版本不再支持IE9以下的浏览器

Jquery Ajax-方法
基于JqueryAjax -demo

通过ajax返回得到的字符串,可以通过  obj = JSON.parse(callback) 转换回原来格式!

跨域AJAX

由于浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取或设置另一个源加载的文档的属性。

特别的:由于同源策略是浏览器的限制,所以请求的发送和响应是可以进行,只不过浏览器不接受罢了。

浏览器同源策略并不是对所有的请求均制约:

  • 制约: XmlHttpRequest

  • 不叼: img、iframe、script等具有src属性的标签  => 相当于发送了get请求

跨域,跨域名访问,如:http://www.c1.com 域名向 http://www.c2.com域名发送请求。

1、JSONP实现跨域请求

JSONP(JSONP - JSON with Padding是JSON的一种“使用模式”),利用script标签的src属性(浏览器允许script标签跨域)

-- localhost:8889 :class MainHandler(tornado.web.RequestHandler):    def get(self):        self.write("func([11,22,33,44])")*******************************************-- localhost:8888 :function Jsonp1(){    var tag = document.createElement('script');    tag.src = 'http://localhost:8889/index';    document.head.appendChild(tag);    document.head.removeChild(tag);}function func(arg) {    console.log(arg)}

Jsonp1() 被执行后,创建了一个<script> 代码块 , 填充了返回值!

1
2
3
<script>
    func([11,22,33,44])
</script>

接着执行了 func() 输出 [11,22,33,44]

-- jQuery 实现方式:
function
jsonpclick() { $.ajax({ url:'http://localhost:8889/index', dataType:'jsonp', jsonpCallback:'func', });}

改进版:

-- localhost:8889 :class MainHandler(tornado.web.RequestHandler):    def get(self):        callback = self.get_argument('callback')        self.write("%s([11,22,33,44])"%callback)此时页面中,访问:http://localhost:8889/index?callback=xxoohttp://localhost:8889/index?callback=ssss都可以!*******************************************-- localhost:8888 :function func(arg) {    console.log(arg)}function jsonpclick() {    $.ajax({        url:'http://localhost:8889/index',        dataType:'jsonp',        jsonp:'callback',        jsonpCallback:'func',    });}

代码中相当于发送了: http://localhost:8889/index?callback=func

1
2
3
4
5
6
jsonp:要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。
该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,
例如 {jsonp:'onJsonPLoad'} 会导致将"?onJsonPLoad="传给服务器。
jsonpCallBack: 区分大小写
实例: 江西电视台节目单获取

2、CORS

随着技术的发展,现在的浏览器可以支持主动设置从而允许跨域请求,

即:跨域资源共享(CORS,Cross-Origin Resource Sharing)

其本质是设置响应头,使得浏览器允许跨域请求。

* 简单请求 OR 非简单请求

1
2
3
4
5
6
7
8
9
10
11
12
13
条件:
    1、请求方式:HEAD、GET、POST
    2、请求头信息:
        Accept
        Accept-Language
        Content-Language
        Last-Event-ID
        Content-Type 对应的值是以下三个中的任意一个
                                application/x-www-form-urlencoded
                                multipart/form-data
                                text/plain
  
注意:同时满足以上两个条件时,则是简单请求,否则为复杂请求

* 简单请求和非简单请求的区别?

1
2
简单请求:一次请求
非简单请求:两次请求,在发送数据之前会先发一次请求用于做“预检”,只有“预检”通过后才再发送一次请求用于数据传输。

* 关于“预检”

1
2
3
4
5
6
7
- 请求方式:OPTIONS
- “预检”其实做检查,检查如果通过则允许传输数据,检查不通过则不再发送真正想要发送的消息
- 如何“预检”
     => 如果复杂请求是PUT等请求,则服务端需要设置允许某请求,否则“预检”不通过
        Access-Control-Request-Method
     => 如果复杂请求设置了请求头,则服务端需要设置允许某请求头,否则“预检”不通过
        Access-Control-Request-Headers

基于cors实现AJAX请求:

a、支持跨域,简单请求

1
2
3
4
5
服务器设置响应头:Access-Control-Allow-Origin = '域名' '*'
self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")
self.set_header('Access-Control-Allow-Origin', "http://localhost:8888,http://localhost:9999")
self.set_header('Access-Control-Allow-Origin', "*")    //所有网站

实例:

function corsSimple() {    $.ajax({        url:'http://localhost:8889/index',        type:'post',        data:{'v1':'k1'},        success:function (callback) {            console.log(callback)        }    });}***********************************************-- localhost:8889def post(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    v1 = self.get_argument('v1')    print(v1)    self.write('--post--')

b、支持跨域,复杂请求

由于复杂请求时,首先会发送“预检”请求,如果“预检”成功,则发送真实数据。

  • “预检”请求时,允许请求方式则需服务器设置响应头:Access-Control-Request-Method

  • “预检”请求时,允许请求头则需服务器设置响应头:Access-Control-Request-Headers

  • “预检”缓存时间,服务器设置响应头:Access-Control-Max-Age

--localhost:8889def options(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Methods', "PUT")    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    print('--option--')def put(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    print('--put--')    self.write('--put--')***********************************************--localhost:8888function corscomplex() {    $.ajax({        url:'http://localhost:8889/index',        type:'put',        data:{'v1':'k1'},        success:function (callback) {            console.log(callback)        }    });}

如果客户端,加上了自定义请求头,服务器端要加上

1
self.set_header('Access-Control-Allow-Headers', "key1,key2")

实例:

--localhost:8889def options(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Methods', "PUT")    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    self.set_header('Access-Control-Allow-Headers', "key1,key2")    self.set_header('Access-Control-Max-Age', 10)    print('--option--')def put(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    print('--put--')    self.write('--put--')***********************************************--localhost:8888function corscomplex() {    $.ajax({        url:'http://localhost:8889/index',        type:'put',        headers:{'key1':'xxx'},        data:{'v1':'k1'},        success:function (callback) {            console.log(callback)        }    });}

控制预检过期时间:

1
self.set_header('Access-Control-Max-Age', 10)   //10

c、跨域传输cookie

在跨域请求中,默认情况下,HTTP Authentication信息,Cookie头以及用户的SSL证书无论在预检请求中或是在实际请求都是不会被发送。

如果想要发送:

  • 浏览器端:XMLHttpRequest的withCredentials为true

  • 服务器端:Access-Control-Allow-Credentials为true

  • 注意:服务器端响应的 Access-Control-Allow-Origin 不能是通配符 *

--localhost:8889def options(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Methods', "PUT")    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    self.set_header('Access-Control-Allow-Credentials', "true")   //必须    print('--option--')def put(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    self.set_header('Access-Control-Allow-Credentials', "true")   //必须print(self.cookies)    self.set_cookie('k1','kkk')    self.write('--put--')***********************************************--localhost:8888function corscomplex() {    $.ajax({        url:'http://localhost:8889/index',        type:'put',        data:{'v1':'k1'},        xhrFields:{withCredentials: true},        success:function (callback) {            console.log(callback)        }    });}    

d、跨域获取响应头

默认获取到的所有响应头只有基本信息,如果想要获取自定义的响应头,则需要再服务器端设置Access-Control-Expose-Headers。

--localhost:8889def options(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Methods', "PUT")    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    self.set_header('Access-Control-Allow-Headers', "key1,key2")    self.set_header('Access-Control-Allow-Credentials', "true")       print('--option--')def put(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Origin', "http://localhost:8888")    self.set_header('Access-Control-Allow-Credentials', "true")       self.set_header('bili', "daobidao")    //设置响应头    self.set_header('Access-Control-Expose-Headers', "xxoo,bili")   //允许发送    print(self.cookies)    self.set_cookie('k1','kkk')    self.write('--put--')***********************************************--localhost:8888function corsRequest() {    $.ajax({        url:'http://localhost:8889/index',        type:'put',        data:{'v1':'k1'},        xhrFields:{withCredentials: true},        success:function (callback,statusText, xmlHttpRequest) {      console.log(callback);      console.log(xmlHttpRequest.getAllResponseHeaders());    }    });}    

示例代码整合:

localhost:8888/index.html
localhost:8889/python

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
ASP.NET Web API
angularjs跨域post解决方案
IIS 支持 ajax 跨域
ajax 跨域 headers JavaScript ajax 跨域请求 +设置headers 实践
记录我开发工作中遇到HTTP跨域和OPTION请求的一个坑
一文带你了解 HTTP 黑科技
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服