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

jquery ajax 跨域解决方案【1分钟】
背景,由于登录服务器和应用服务器不在一个域,所以必须跨域进行登录验证,而AJAX本身是不能跨域的,但jquery提供了默认的解决方案。

第一步,服务端:

String callback=request.getParameter("callback");
JSONObject jb = JSONObject.fromObject(result);// 更改为你自己的拼装JSON代码
PrintWriter out = response.getWriter();

out.print(callback+"("+jb.toString()+")",false);
out.close();
return null;
		


第二部,客户端:

_Jquery.ajax({
            		url    : url,
            		data   : data,
            		dataType : "jsonp",
            		jsonnp : 'callback',
            		timeout:15,
            		success : function(map){
            			if(map["success"]=="true"){
		                	_dialogAlert("登录成功!",'登录成功');
		                	location.reload();
            			}else{
            				_dialogAlert(map["errorMsg"],'登录失败');
            			}
            		},
            		error:function (XMLHttpRequest, textStatus, errorThrown) {
    // 通常 textStatus 和 errorThrown 之中
    // 只有一个会包含信息
    _dialogAlert("请求超时,请稍后重试。"); // 调用本次AJAX请求时传递的options参数
}
            	});