$.getJSON()跨域之原理

來源:互聯網
上載者:User

/*可以跨域請求資料*/

其原理是對<script>裝載的服務端資料用全域函數(callback)操作

首先寫個簡單樣本:(jsonpCallback可動態建立註冊成全域函數)

<script type="text/javascript">  
var m = Math.random();
var jsonpCallback = new Function("result", "alert(result.data);");
</script>  
<script type="text/javascript" src="http://localhost/json.php?jsonp=jsonpCallback"></script>  

 

服務端:

<?php
echo "jsonpCallback({data:'json data'})"; 

 

會彈出:json data

 

 

$.get(url, params, callback)

與$.post要求方法一樣,只是請求類型不同

返回的是字元格式設定,可以用 $.evalJSON()方法進行轉換格式

然後對JSON對象進行操作

$.getJSON(url, params, callback)

返回JSON對象,跨域樣本如下:

  1. <?php

  2. function getdata()

  3. {

  4.         $.getJSON(

  5.         "http://www.test.com/payment/payment/paytest?callback=?",

  6.         {id:1,name:"name"},

  7.         function(jsondata){

  8.                 alert(jsondata.json);

  9.         });

  10. }

  11. 翻開jquery.的源碼,一步步找:

  12. getJSON: function( url, data, callback ) {

  13.         return jQuery.get(url, data, callback, "json");

  14. }

  15. 再找JQuery.get

  16. get: function( url, data, callback, type ) {

  17.         // shift arguments if data argument was omited

  18.         if ( jQuery.isFunction( data ) ) {

  19.                 type = type || callback;

  20.                 callback = data;

  21.                 data = null;

  22.         }

  23.         return jQuery.ajax({

  24.                 type: "GET",

  25.                 url: url,

  26.                 data: data,

  27.                 success: callback,

  28.                 dataType: type

  29.         });

  30. }

  31. 再找 jQuery.ajax

  32. jQuery.ajax({

  33.         url: url,

  34.         type: type,

  35.         dataType: "html",

  36.         data: params,

  37.         complete: function( res, status ) {

  38.                 // If successful, inject the HTML into all the matched elements

  39.                 if ( status === "success" || status === "notmodified" ) {

  40.                         // See if a selector was specified

  41.                         self.html( selector ?

  42.                         // Create a dummy div to hold the results

  43.                         jQuery("<div />")

  44.                         // inject the contents of the document in, removing the scripts

  45.                         // to avoid any 'Permission Denied' errors in IE

  46.                         .append(res.responseText.replace(rscript, ""))

  47.                         // Locate the specified elements

  48.                         .find(selector) :

  49.                         // If not, just inject the full result

  50.                         res.responseText );

  51.                 }

  52.                 if ( callback ) {

  53.                         self.each( callback, [res.responseText, status, res] );

  54.                 }

  55.         }

  56. });

  57. return this;

  58. }

  59. 再找ajax方法,揭開秘密要來了:

  60. 由於太多,帖開頭部分,有興趣的同學自己去看下

  61. ajax: function( origSettings ) {

  62.         var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);

  63.         var jsonp, status, data,

  64.         callbackContext = origSettings && origSettings.context || s,

  65.         type = s.type.toUpperCase();

  66.         // convert data if not already a string

  67.         if ( s.data && s.processData && typeof s.data !== "string" ) {

  68.                 s.data = jQuery.param( s.data, s.traditional );

  69.         }

  70.         比較重要的一部分:

  71.         http://localhost/index/ajax?callback=jsonp1274437815229&id=1

  72.         伺服器判斷是否有這個callback參數,如果有就返回JS函數名+對象

  73.         //jsonp = jsonp1274437815229(請求地址的回調參數)

  74.         //jsonp全域函數

  75.         window[ jsonp ] = window[ jsonp ] || function( tmp ) {

  76.                 data = tmp;

  77.                 success();

  78.                 complete();

  79.                 // Garbage collect

  80.                 window[ jsonp ] = undefined;

聯繫我們

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