深入理解jsonp跨域請求原理

來源:互聯網
上載者:User

標籤:

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

  一、jsop  

  二、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函數的調用,並且將服務端資料以該函數參數的形式傳遞過來。

1  <script>2        function fuc(data){3          console.log(data.name);4         }5      </script>6      <script src="http://www.baidu.com/api.php?callback=fuc"></script>    
4、後台代碼
1 <?php2     $cb = $_GET[‘callback‘];3     $data = array(4                 ‘name‘=> ‘zs‘,5                 ‘age‘=>18,6                 ‘gender‘=>true7             );8     echo $cb.‘(‘.json_encode($data).‘)‘;9 ?>    
案例:利用jsonp訪問百度天氣
 1   $(function () { 2         // 發送jsonp請求 3         $.ajax({ 4             type:"get", 5             url:‘http://api.map.baidu.com/telematics/v3/weather?output=json&ak=0A5bc3c4fb543c8f9bc54b77bc155724‘, 6             data:{ 7                 location:$("#city").val()||"上海" 8             }, 9             dataType:"jsonp",10             success: function (data) {11                 //渲染模版12                 var html = template(‘template‘,{list:data.results[0].weather_data})13                 $(‘tbody‘).html(html);14 15             }16         });17     });
  使用template載入資料
<script type="text/template" id="template">      <% for(var i=0 ; i< list.length ;i++){ %>          <tr>          <% var item = list[i]; %>          <td><%=item.date%></td>          <td><img src="<%=item.dayPictureUrl%>" /></td>          <td><img src="<%=item.nightPictureUrl%>" /></td>          <td><%=item.temperature%></td>          <td><%=item.weather%></td>          <td><%=item.wind%></td>          </tr>       <%}%></script>
  :

 

深入理解jsonp跨域請求原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.