Python學習---JSONP學習180130

來源:互聯網
上載者:User

標籤:import   attr   min   遠程服務   add   lse   smart   htm   tabs   

同源策略機制

     同源:協議://IP:連接埠協議,網域名稱,連接埠相同

     跨域:知道對方介面,同時對方返回的資料也必須是Jsonp格式的

問題描述:Ajax跨域請求資料的時候,實際瀏覽器已經拿到資料,但是瀏覽器由於同源策略隱藏了這些內容,不給我們看這些資料。換言之,Ajax不能跨域請求資料。

問題解決:<script src="">

           有src屬性的標籤都可以跨域請求資料,這也就是為什麼img我們可以引用別的網站的圖片

JSONP的原型:建立一個回呼函數,然後在遠程服務上調用這個函數並且將JSON 資料形式作為參數傳遞,完成回調。

JSONP一定是GET請求

Jsonp執行個體一: 利用script標籤的src屬性

padding: 就是函數,將資料放在在函數內,然後打包發送給前台、

缺點:前台script裡必須要有一個函數,處理一個寫一個函數,因為本質是利用函數接收參數

         正確應該動態添加script標籤和內容

settigs.py:

‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],  # 設定templates的路徑為Django以前版本# ‘DIRS‘: [],      # 注釋掉該行,此為Django 2.0.1最新版本# ‘django.middleware.csrf.CsrfViewMiddleware‘,         ...省略預設配置STATIC_URL = ‘/static/‘TEMPLATE_DIRS = (os.path.join(BASE_DIR,  ‘templates‘),)  # 原配置# 靜態資源檔案STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 現添加的配置,這裡是元組,注意逗號

templates/ajax_jquery.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8"></head><script src="/static/jquery-3.2.1.js"></script><script>    function test(data) {        console.log(data)    }</script>{#跨站請求內容#}<script src="http://127.0.0.1:8081/jquery_ajax_test/"></script></html>

mysite2/urls.py

from django.contrib import adminfrom django.urls import pathfrom blog import viewsfrom django.conf.urls import urlurlpatterns = [      # Jquery_Ajax  url(r‘ajax-jquery/‘, views.ajax_jquery),  # jquery_ajax_test  url(r‘jquery_ajax_test/‘, views.jquery_ajax_test),]

views.py

from django.shortcuts import render, HttpResponse# Jquery --> ajaxdef ajax_jquery(request):    return render(request, ‘ajax_jquery.html‘)# Jquery --> ajaximport jsondef jquery_ajax_test(request):    print(‘request.POST‘, request.POST)    # return HttpResponse(‘hello‘)   # 錯誤,此時跨域返回給scrip標籤一個未定義的hello變數     # return HttpResponse(‘var hello‘)   # 正確,此時跨域返回給scrip標籤一個定義但沒有內容的hello變數    return HttpResponse(‘test("hello")‘)

頁面顯示:

動態建立script的JSonp執行個體:

settigs.py:

‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],  # 設定templates的路徑為Django以前版本# ‘DIRS‘: [],      # 注釋掉該行,此為Django 2.0.1最新版本# ‘django.middleware.csrf.CsrfViewMiddleware‘,         ...省略預設配置STATIC_URL = ‘/static/‘TEMPLATE_DIRS = (os.path.join(BASE_DIR,  ‘templates‘),)  # 原配置# 靜態資源檔案STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 現添加的配置,這裡是元組,注意逗號

templates/ajax_jquery.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8"></head><body>    <button onclick="f()">submit</button></body><script src="/static/jquery-3.2.1.js"></script>{#動態跨站請求內容#}<script>    function addScriptTag(src){     var script = document.createElement(‘script‘);         script.setAttribute("type","text/javascript");         script.src = src;         document.body.appendChild(script);        {# document.body.removeChild(script); #}    }    function SayHi(arg){         alert("Hello " + arg)    }    function f(){         addScriptTag("http://127.0.0.1:8081/jquery_ajax_test/?callback=SayHi")    }</script></html>

mysite2/urls.py

from django.contrib import adminfrom django.urls import pathfrom blog import viewsfrom django.conf.urls import urlurlpatterns = [      # Jquery_Ajax  url(r‘ajax-jquery/‘, views.ajax_jquery),  # jquery_ajax_test  url(r‘jquery_ajax_test/‘, views.jquery_ajax_test),]

views.py

from django.shortcuts import render, HttpResponse# Jquery --> ajaxdef ajax_jquery(request):    return render(request, ‘ajax_jquery.html‘)# Jquery --> ajaxdef jquery_ajax_test(request):    print(‘request.GET‘, request.GET)    func = request.GET.get(‘callbacks‘, None)    print(‘func;‘, func)    return HttpResponse("%s(‘world‘)" % func)

頁面顯示:

注意:

這裡運行了2個環境: python manage.py runserver 8081

項目本身是:http://127.0.0.1:8080/ajax-jquery/

jQuery對JSONP的實現

 

1. 使用Jquery定義的回呼函數名:

$.getJSON("http://127.0.0.1:8081/jquery_ajax_test?callback=?",function(arg){    console.log("successfully, hello " + arg)});

注意的是在url的後面必須添加一個callback參數,這樣getJSON方法才會知道是用JSONP方式去訪問服務,callback後面的那個問號是內部自動產生的一個回呼函數名。

  2.  使用自訂的函數名:

形式一: 自訂函數 + 調用指定函數 【不推薦】function SayHi() {      ...}$.ajax({    url:"http://127.0.0.1:8002/get_byjsonp",    dataType:"jsonp",  # 要求伺服器返回一個JSONP格式的資料,一個函數套著一個資料形式,否則返回原類型    jsonp: ‘callback‘,    jsonpCallback:"SayHi"});注意:jsonp: ‘callback‘ + jsonpCallback:"SayHi"  --拼湊一個索引值對發送過去---->  ‘callback‘:‘SayHi‘形式二:自訂函數 + 不用指定函數名  【推薦】$.ajax({    url:"http://127.0.0.1:8002/get_byjsonp",    dataType:"jsonp",            //必須有,告訴server,這次訪問要的是一個jsonp的結果。    jsonp: ‘callback‘,          //jQuery協助隨機產生的:callback="wner"    success:function(data){  # 接收後台傳遞過來的data資料即可        alert(data)     }});

getJSON使用JQuery定義的函數名--執行個體

settigs.py:

‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],  # 設定templates的路徑為Django以前版本# ‘DIRS‘: [],      # 注釋掉該行,此為Django 2.0.1最新版本# ‘django.middleware.csrf.CsrfViewMiddleware‘,         ...省略預設配置STATIC_URL = ‘/static/‘TEMPLATE_DIRS = (os.path.join(BASE_DIR,  ‘templates‘),)  # 原配置# 靜態資源檔案STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 現添加的配置,這裡是元組,注意逗號

templates/ajax_jquery.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <button onclick="f()">submit</button></body><script src="/static/jquery-3.2.1.js"></script>{# jQuery對JSONP的實現#}<script type="text/javascript">   function f() {    $.getJSON("http://127.0.0.1:8081/jquery_ajax_test?callback=?",function(arg){        console.log("successfully, hello " + arg)    });}</script></html>

mysite2/urls.py

from django.contrib import adminfrom django.urls import pathfrom blog import viewsfrom django.conf.urls import urlurlpatterns = [      # Jquery_Ajax  url(r‘ajax-jquery/‘, views.ajax_jquery),  # jquery_ajax_test  url(r‘jquery_ajax_test/‘, views.jquery_ajax_test),]

views.py

from django.shortcuts import render, HttpResponse# Jquery --> ajaxdef ajax_jquery(request):    return render(request, ‘ajax_jquery.html‘)# Jquery --> ajaxdef jquery_ajax_test(request):    print(‘request.GET‘, request.GET)    func = request.GET.get(‘callback‘, None)    print(‘func;‘, func)    return HttpResponse("%s(‘world 2020‘)" % func)

頁面顯示:

getJSON使用自訂的函數名--執行個體:

settigs.py:

‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],  # 設定templates的路徑為Django以前版本# ‘DIRS‘: [],      # 注釋掉該行,此為Django 2.0.1最新版本# ‘django.middleware.csrf.CsrfViewMiddleware‘,         ...省略預設配置STATIC_URL = ‘/static/‘TEMPLATE_DIRS = (os.path.join(BASE_DIR,  ‘templates‘),)  # 原配置# 靜態資源檔案STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 現添加的配置,這裡是元組,注意逗號

templates/ajax_jquery.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <button onclick="f()">submit</button></body><script src="/static/jquery-3.2.1.js"></script>{# jQuery對JSONP的實現#}<script type="text/javascript">    $.getJSON("http://127.0.0.1:8081/jquery_ajax_test?callback=?",function(arg){        console.log("successfully, hello " + arg)    });</script></html>

mysite2/urls.py

from django.contrib import adminfrom django.urls import pathfrom blog import viewsfrom django.conf.urls import urlurlpatterns = [      # Jquery_Ajax  url(r‘ajax-jquery/‘, views.ajax_jquery),  # jquery_ajax_test  url(r‘jquery_ajax_test/‘, views.jquery_ajax_test),]

views.py

from django.shortcuts import render, HttpResponse# Jquery --> ajaxdef ajax_jquery(request):    return render(request, ‘ajax_jquery.html‘)# Jquery --> ajaxdef jquery_ajax_test(request):    print(‘request.GET‘, request.GET)    func = request.GET.get(‘callback‘, None)    print(‘func;‘, func)    return HttpResponse("%s(‘world 2020‘)" % func)

頁面顯示:

.ajax 跨域請求之指定函數

settigs.py:

‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],  # 設定templates的路徑為Django以前版本# ‘DIRS‘: [],      # 注釋掉該行,此為Django 2.0.1最新版本# ‘django.middleware.csrf.CsrfViewMiddleware‘,         ...省略預設配置STATIC_URL = ‘/static/‘TEMPLATE_DIRS = (os.path.join(BASE_DIR,  ‘templates‘),)  # 原配置# 靜態資源檔案STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 現添加的配置,這裡是元組,注意逗號

templates/ajax_jquery.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <button onclick="f()">submit</button></body><script src="/static/jquery-3.2.1.js"></script>{# jQuery對JSONP的實現#}<script type="text/javascript">    function SayHi() {        console.log("hello, json")    }    function f() {        $.ajax({        url:"http://127.0.0.1:8081/jquery_ajax_test",        dataType:"jsonp",        jsonp: ‘callback‘,        jsonpCallback:"SayHi"   });}</script></html>

mysite2/urls.py

from django.contrib import adminfrom django.urls import pathfrom blog import viewsfrom django.conf.urls import urlurlpatterns = [      # Jquery_Ajax  url(r‘ajax-jquery/‘, views.ajax_jquery),  # jquery_ajax_test  url(r‘jquery_ajax_test/‘, views.jquery_ajax_test),]

views.py

from django.shortcuts import render, HttpResponse# Jquery --> ajaxdef ajax_jquery(request):    return render(request, ‘ajax_jquery.html‘)# Jquery --> ajaxdef jquery_ajax_test(request):    print(‘request.GET‘, request.GET)    func = request.GET.get(‘callback‘, None)    return HttpResponse("%s(‘world 2020‘)" % func)   # func為[],因為根本不需要調用,前台已定義好

頁面顯示:

Python學習---JSONP學習180130

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.