码迷,mamicode.com
首页 > Web开发 > 详细

使用jsonp进行跨域访问

时间:2014-07-22 00:04:35      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   java   使用   os   

一、使用场景

  当我们请求非本服务器的资源的时候,浏览器会禁止访问,并提示不允许跨域访问。此时我们可以使用jsonp这种请求方式,从其他服务器获取资源。在客户端调用提供jsonp支持的接口,获取jsonp格式的数据。

二、客户端的实现

  客户端使用jsp,用js发送ajax请求,代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">
		<title>jsonp</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<script type="text/javascript" src="./js/jquery-1.9.1.min.js"></script>
</head>
<body>
		<script type="text/javascript">
jQuery(document).ready(function() {

	$.ajax( {
		type : "get",
		async : false,
		url : "http://127.0.0.1:8089/test2/TestServlet?id=1",
		dataType : "jsonp",
		jsonp : "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
		jsonpCallback : "Tcallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
		success : function(json) {
			alert(‘name: ‘ + json.name + ‘,age: ‘ + json.age);
		},
		error : function() {
			alert(‘fail‘);
		}
	});

});
</script>
</body>
</html>

  此段代码相当于get请求http://127.0.0.1:8089/test2/TestServlet?id=1&callback=Tcallback .

三、服务器实现

  服务器端使用servlet实现,代码如下:

public class TestServlet extends HttpServlet
{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String id = request.getParameter("id");
		String callback = request.getParameter("callback");//值为Tcallback 
		String name = "zhangsan";
		int age = 20;
		String json = String.format("%s({\"name\":\"%s\", \"age\":%s})",
				callback, name, age);//返回的数据
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
		out.close();
	}
}

使用jsonp进行跨域访问,布布扣,bubuko.com

使用jsonp进行跨域访问

标签:des   blog   http   java   使用   os   

原文地址:http://www.cnblogs.com/always-online/p/3859340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!