【转载】JavaScript跨域

使用JQuery Json的兄弟们经常会碰到这样的问题,使用AJAX往远程服务端发送请求,获取JSON数据并在前台页面进行操作。而这时前台往往会出现js错误,拒绝访问。这是为什么?
首先我们必须明白json是基于Javascript实现的

其次需要了解关于网站的同源策略,什么是同源策略?
同源策略是客户端脚本(尤其是Javascript)的重要安全度量标准,它是由Netscape提出的一个著名的安全策略,现在所有的可支持javascript的浏览器都使用这个策略。同源策略不允许来自于其它站点的脚本运行于本站点之中。为什么要使用同源策略呢?
假如没有同源策略,众所周知,JavaScript可以做很多事情,比如:读取/修改网页中某个值。假设浏览器同时打开两个网站,一个是银行网站,另一个是专门盗取银行信息的恶意网站,如果没有同源策略,恶意网站可以轻易盗取用户的用户名和密码,这个后果是很严重的

最后,我们来说说怎么解决这个问题,达到间接跨域访问的目的
首先必须明白一点跨域的安全限制都是指浏览器端来说的.服务器端是不存在跨域安全限制的。
可从这一点切入,通过后台作为一个代理,接受远程站点返回的数据再返回前台而面,达到“同源”的目的。
具体代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doPost(request, response);
}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		boolean requestType = false;// 标记远程请求类型,默认为GET方式
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		Enumeration keys = req.getParameterNames();// 取出客户端传入的所有参数名
		ArrayList<String> params = new ArrayList<String>();
		String url = ""; // 远程地址
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();

			params.add(key);// 其它加入参数列表,此处为参与远程请求的参数
			requestType = true;// 修改标记,表求远程请求为POST方式

		}

		HttpClient client = new HttpClient();
		HttpMethod method = null;
		if (requestType) {// 判断请求方式,并实例化HttpMethod对象,true:POST,false:GET
			method = new UTF8PostMethod(url);
			for (String name : params) {// 迭代POST参数,加入到请求中
				String _value = req.getParameter(name);
				// System.out.println(name+"="+_value);
				((PostMethod) method).setParameter(name, _value);
			}
		} else {
			method = new GetMethod(url);
		}
		client.executeMethod(method);// 执行请求
		String bodystr = method.getResponseBodyAsString();// 返回结果
		out.println(bodystr);// 将结果返回给客户端
	}

	/**
	 * 内部类,转换URL字符串为UTF-8
	 * 
	 * @author Administrator
	 * 
	 */
	private static class UTF8PostMethod extends PostMethod {
		public UTF8PostMethod(String url) {
			super(url);
		}

		@Override
		public String getRequestCharSet() {
			return "UTF-8";
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}

相关推荐