jquery ajax 跨域

具体方法:

非跨域的方式:
客户端

$.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来加载数据,无法直接获得数据,所以需要使用回调函数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值