ajax跨域请求

1、httpclient代理处理跨域请求。

1.1、请求服务器的xml

(1)服务器端

CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpGet httpGet = new HttpGet("http://fanyi.youdao.com/openapi.do?keyfrom=<keyfrom>&key=<key>&type=data&doctype=xml&version=1.1&q="+request.getParameter("q"));

		try {

			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

			HttpEntity entity = httpResponse.getEntity();

			if(entity !=null){

				String tmp = EntityUtils.toString(entity);

				httpResponse.close();

				response.setContentType("text/xml;charset=utf-8");

				PrintWriter out = response.getWriter();

				out.print(tmp);

				out.flush();

				out.close();

			}

		} catch (Exception e) {

			e.printStackTrace();

			System.out.println(e.getMessage());

		}finally{

		}

 (2)客户端

$.ajax({

					type:"get",

					url:"/Ajax/fanyi.do",

					data:"q=good",

					success:function(xml){

						var data = "";

						data += $(xml).find("query").text();

						data += $(xml).find("translation").text();

						data += $(xml).find("basic").text();

						$("#status").text(data);

					}

				});

1.2 请求服务器的json格式

(1)服务器端

CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpGet httpGet = new HttpGet("http://fanyi.youdao.com/openapi.do?keyfrom=<keyfrom>&key=<key>&type=data&doctype=json&version=1.1&q="+request.getParameter("q"));

		try {

			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

			HttpEntity entity = httpResponse.getEntity();

			if(entity !=null){

				String tmp = EntityUtils.toString(entity);

				httpResponse.close();

				response.setContentType("application/json;charset=utf-8");

				PrintWriter out = response.getWriter();

				out.print(tmp);

				out.flush();

				out.close();

			}

		} catch (Exception e) {

			e.printStackTrace();

			System.out.println(e.getMessage());

		}finally{

		}

(2)客户端

$.ajax({

					type:"get",

					url:"/Ajax/fanyi.do",

					data:"q=good",

					success:function(data){

						$("#status").text(data.translation);

					}

				});

  

你可能感兴趣的:(AJAX跨域)