jquery 跨域访问问题
jquery ajax 本身是不无法进行跨域访问的,不过jquery提供了jsonp 属性,可以jsonp协议试下跨域访问,下面给出一个简单的实例。
1)jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><% String a ="{'name':'tom','sex':'男','age':'24'}"; String json = request.getParameter("callback"); json = json +"("+a+")"; response.getWriter().write(json);%>
<script type="text/javascript"> $(function(){ $.ajax({ async:false, url: 'http://localhost:8080/ws/web/pages/data/json.jsp', type: "GET", dataType: 'jsonp', jsonp: 'callback', data: null, success: function (json) { alert(json.name);} }); }) </script>
package cn.com.ld.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;/** * @filename: HttpAccessProxy * @Description: TODO * @author java小生 * @date 2012-9-13 下午4:09:56 */public class HttpAccessProxy {public static String accessProxy(String pageUrl) {URL url;String pageString = "";InputStream is = null;BufferedReader br = null;StringBuffer sb = null;try {url = new URL(pageUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();is = connection.getInputStream();br = new BufferedReader(new InputStreamReader(is));sb = new StringBuffer();String line = null;while ((line = br.readLine()) != null) {sb.append(line + "\n");}pageString = sb.toString();} catch (Exception e) {e.printStackTrace();} finally {try {is.close();br.close();} catch (IOException e) {e.printStackTrace();}}return pageString;}public static void main(String[] args) {System.out.println(HttpAccessProxy.accessProxy("http://localhost:8080/ws/web/pages/data/json.jsp"));}}