/*可以跨域请求数据*/
其原理是对<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;