日期:2014-05-16  浏览次数:20345 次

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+")");
		
	}