1. 程式人生 > 其它 >jsonp跨域請求原理

jsonp跨域請求原理

技術標籤:jsonpajaxhttp

jsonp跨域請求原理

今天咱們講講jsonp跨域請求原理吧!

在進行網站開發的過程中經常會用到第三方的資料,但是由於同源策略的限制導致ajax不能傳送請求,因此也無法獲得資料。解決ajax的跨域問題有兩種方法:
一、jsonp

二、XMLHttpRequest2中可以配合服務端來解決,在響應頭中加入Access-Control-Allow-Origin:*

1、同源:

同源策略是瀏覽器的一種安全策略,所謂同源是指,域名,協議,埠號完全相同
  1.1目的:保護使用者資訊保安
  1.2限制:cookie、localStorage和IndexDB無法讀取

  無法操作跨域的iframe裡的dom元素
  ajax請求不能傳送
2、跨域:

不同源則為跨域

(1) http://api.example.com/detail.html 不同源 域名不同
(2) https//www.example.com/detail.html 不同源 協議不同
(3) http://www.example.com:8080/detail.html 不同源 埠不同
(4) http://api.example.com:8080/detail.html 不同源 域名、埠不同
(5) https://api.example.com/detail.html 不同源 協議、域名不同
(6) https://www.example.com:8080/detail.html 不同源 埠、協議不同

(7) http://www.example.com/detail/index.html 同源 只是目錄不同

3、jsonp原理:

其本質是利用了標籤具有可跨域的特性,由服務端返回預先定義好的javascript函式的呼叫,並且將服務端資料以該函式引數的形式傳遞過來

4、案例

<!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 src="/static/js/jquery-1.12.4.js"></script> <script> function getContent(){ /* ajax原生方式傳送 var xhr = new XMLHttpRequest(); xhr.open('GET','http://wupeiqi.com:8001/jsonp.html?k1=v1&k2=v2'); xhr.onreadystatechange = function(){ console.log(xhr.responseText); }; xhr.send(); */ /* var tag = document.createElement('script'); tag.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403'; document.head.appendChild(tag); document.head.removeChild(tag); */ $.ajax({ url: 'http://www.jxntv.cn/data/jmd-jxtv2.html', //江西電視臺的url type: 'POST', //請求方式為POST dataType: 'jsonp', //資料格式為jsonp jsonp: 'callback', jsonpCallback: 'list' //表示url的callback等於list,會額外的通過url發過去 }) } function list(arg){ console.log(arg); } </script> </body> </html>

今天就到 這兒吧!下課。。。。。