/*可以跨域請求資料*/
其原理是對<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對象,跨域樣本如下:
<?php
function getdata()
{
$.getJSON(
"http://www.test.com/payment/payment/paytest?callback=?",
{id:1,name:"name"},
function(jsondata){
alert(jsondata.json);
});
}
翻開jquery.的源碼,一步步找:
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
}
再找JQuery.get
get: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
}
再找 jQuery.ajax
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function( res, status ) {
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div />")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}
if ( callback ) {
self.each( callback, [res.responseText, status, res] );
}
}
});
return this;
}
再找ajax方法,揭開秘密要來了:
由於太多,帖開頭部分,有興趣的同學自己去看下
ajax: function( origSettings ) {
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
var jsonp, status, data,
callbackContext = origSettings && origSettings.context || s,
type = s.type.toUpperCase();
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
比較重要的一部分:
http://localhost/index/ajax?callback=jsonp1274437815229&id=1
伺服器判斷是否有這個callback參數,如果有就返回JS函數名+對象
//jsonp = jsonp1274437815229(請求地址的回調參數)
//jsonp全域函數
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;