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

jsoup方式解决跨域
客户端:
<html>
<head>
<meta http-equiv="content-Type" content="text/html;charset=UTF-8">
<title>跨域</title>
<script type="text/javascript" src="../jquery1.4.2.js"></script>
<script language="JavaScript" type="text/javascript">
function apply()
{
var name= $("#name").val();
var mobile = $("#mobile").val();
var message = $("#message").val();
if (name == "")
{
   alert("姓名不能为空")
   return;   
}
if (mobile == "")
{
   alert("电话不能为空")
   return;
}
$.ajax({
    type : "get", 
     async:false, 
     url: "http://b.a.com/user/add.do", 
     dataType : "jsonp",
     jsonp: "callbackparam",
     jsonpCallback: "success_register",//回调函数
     contentType:"application/x-www-form-urlencoded; charset=UTF-8",
     data:"name="+name+"&mobile="+mobile+"&message="+message,
     success : function(json){},
error : function(){}
});
}

function success_register(json) {
alert(json.msg);
$("#name").val("");
$("#mobile").val("");
$("#message").val("");
}
</script>
</head>
<body>
<!--把下面代码加到<body>与</body>之间-->
<input type="text" id="name" value="" maxlength="20"/>
<input type="text" id="mobile" value="" maxlength="20"/>
<input type="text" id="message" value="" maxlength="20"/>
<input id="input1" type="button" onclick="apply()">
</body>
</html>


服务器端:
public void add() throws IOException {
String callbackparam = ServletActionContext.getRequest().getParameter("callbackparam");
//业务实现
str="ok";
this.writeHtml(callbackparam + "({msg:\""+str+"\"})");
}

private void writeHtml(String str) {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter out = response.getWriter();
			out.println(str);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}