JSONP產生背景
1.跨域的安全限制都是對瀏覽器端來說的,服務器端是不存在跨域安全限制的。
2.瀏覽器的同源策略限制從一個源加載的文檔或腳本與來自另一個源的資源進行交互。
3.如果協議,端口和主機對於兩個頁面是相同的,則兩個頁面具有相同的源,否則就是不同源的。
4.如果要在js里發起跨域請求,則要進行一些特殊處理了。或者,你可以把請求發到自己的服務端,再通過后台代碼發起請求,再將數據返回前端。也可以通過我們今天講解的JSONP方式在前端頁面進行請求。
環境:
python3.7
django2.x
例子
1.通過后台服務端進行對其他域的請求:
urls.py
1 from django.contrib import admin 2 from django.urls import path,re_path,include 4 from app02 import views as views2 5 6 urlpatterns = [ 7 path('admin/', admin.site.urls), 8 path("req/",views2.req) 9 ]
views.py
1 from django.shortcuts import render 2 import requests 3 # Create your views here. 4 def req(request): 5 response = requests.get("http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=14543768704003") 6 response.content # 字節類型的 7 response.encoding = 'utf-8' 8 print(response.text) #字符串類型 9 return render(request,'req.html',{"result":response.text})
req.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>后台獲取結果</h1> {{ result }} </body> </html>
2.通過XHR直接發送GET進行跨域的請求:
req.html

1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>后台獲取結果</h1> 9 {{ result }} 10 <h1>JS直接獲取結果</h1> 11 <input type="button" value="獲取數據" onclick="getContent();"> 12 <div id="container"></div> 13 <script> 14 function getContent(){ 15 var xhr = new XMLHttpRequest(); 16 xhr.open('GET','http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=14543768704003'); 17 xhr.onreadystatechange = function(){ 18 console.log(xhr.responseText); 19 } 20 xhr.send(); 21 </script> 22 </body> 23 </html>
3.通過XHR模擬JSONP進行跨域的請求:
req.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>后台獲取結果</h1> {{ result }} <h1>JS直接獲取結果</h1> <input type="button" value="獲取數據" onclick="getContent();"> <div id="container"></div> <script> function getContent(){ var tag = document.createElement('script'); tag.src= 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=14543768704003'; document.head.appendChild(tag); // 表示創建一個標簽,並且放到head中 document.head.removeChild(tag); } function list(arg){ console.log(arg); } </script> </body> </html>