具体方法:
非跨域的方式:
客户端
$.getJSON('test.php',null,function (json){
alert(json.a);
});
服务端 :
require('JSON.php');
$json = new Services_JSON();
$info = array('a'=>1);
echo .$json->encode($info);
//实际输出 {"a":1}
跨域的方式:
客户端
$.getJSON('http://slow-live.com/test.php?jsoncallback=?',function (json){//区别在于增加jsoncallback传递回访函数?代表由jquery来指定
alert(json.a);
服务端:
require('JSON.php');
$json = new Services_JSON();
$info = array('a'=>1);
echo $_REQUEST['jsoncallback'].'('.$json->encode($info).')';
//服务端的区别不是直接输出数据,把回访函数加上
//实际输出 jsonp1237114865030({"a":1})
实际上跨域是通过动态增加script来加载数据,无法直接获得数据,所以需要使用回调函数。
非跨域的方式:
客户端
$.getJSON('test.php',null,function (json){
alert(json.a);
});
服务端 :
require('JSON.php');
$json = new Services_JSON();
$info = array('a'=>1);
echo .$json->encode($info);
//实际输出 {"a":1}
跨域的方式:
客户端
$.getJSON('http://slow-live.com/test.php?jsoncallback=?',function (json){//区别在于增加jsoncallback传递回访函数?代表由jquery来指定
alert(json.a);
});
或
$.ajax({
type : "get",
async:false,
url : "http://www.xxx.com/index.php?listid=9",
dataType : "jsonp",
jsonp: "jsoncallback",//服务端用于接收callback调用的function名的参数 相当于 jsoncallback = ?
//jsonpCallback:"success_jsonpCallback",//callback的function名称
beforeSend : function(){
$('<p id=loading_img><img src="loading.gif" width=20 height=20 /></p>').appendTo("#result_yue");
},
success : function(data){
response(data,"#result_yue")
},
error:function(){
$("#result_yue").html('出错了');
}
});
//成功返回处理函数
function response(json,dom_id){
$("p").remove("#loading_img");
$.each(json, function(i,item){
$("<p>",{
id : "title_"+json[i].id,
text : function(){
$("<a href='#news_page' data-transition='slide'>"+json[i].title+"</a>").appendTo(this);
},
click : function(){
$("#news_title").html(json[i].title);
$("#news_content").html(json[i].content);
}
}).appendTo(dom_id);
});
}
服务端:
require('JSON.php');
$json = new Services_JSON();
$info = array('a'=>1);
echo $_REQUEST['jsoncallback'].'('.$json->encode($info).')';
//服务端的区别不是直接输出数据,把回访函数加上
//实际输出 jsonp1237114865030({"a":1})
实际上跨域是通过动态增加script来加载数据,无法直接获得数据,所以需要使用回调函数。