ajax 跨域请求问题 jquery jsonp

最近在项目中面临 ajax 跨域请求问题。

和同事讨论半天,网上查贴一二,附上解决方案

 

 

<script>
$(document).ready(
	function(){
		$("#testBtn").bind("click",loginFun);
		//$("#loginBtn").bind("click",loginFun);
		//$("#setLoginBtn").bind("click",setLoginPas);
		
	}
)
function loginFun(){
	alert(111)
$.ajax({
	type:'get',
	url:'http://127.0.0.1:8080/ttc/twoDimensionalCodeAction/testAjaxCrossDomain.htm',
	beforeSend: function(XMLHttpRequest) {
	},
	data:"lokey=7758521",
	dataType:'jsonp',
	jsonp: 'jsoncallback',
	success:function(data){
		alert(data.keyAlive);
		            
	},
	error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert(errorThrown);
		}
})

}

</script>

 

服务器端代码:

 

public void testAjaxCrossDomain(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		System.out.println("接收跨域请求");
		String loKey = RequestGetString.getString(request, "lokey");
		System.out.println("loKey:"+loKey);
		String jsoncallback = RequestGetString.getString(request, "jsoncallback");
		PrintWriter out = null;
        out = response.getWriter();
        JSONObject json = new JSONObject();
        Random rand = new Random(); 
        int i = rand.nextInt(100);
        StringBuffer abc = new StringBuffer("0123456789");
        for(int j = 0;j<100000;j++){
        	abc.append("0123456789").append("-").append(j).append("-").append("\n");
        }
		json.put("keyAlive", Integer.toString(i)+" "+loKey+" "+abc.toString());
        out.print(jsoncallback+"("+json+")");
		
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值