1) 什么是JSONP?
JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)。
2) 如何使用JSONP?
1. 在客户端调用提供JSONP支持的URL Service,获取JSONP格式数据。
比如客户想访问http://www.myserver.com/myService.aspx?jsonp=callbackFunction
//这个“json”是服务提供端规定好了的字符,不能改 “callbackFunction”是调用者回调的函数,是调用者决定的,可以改
假设客户期望返回JSON数据:[“customername1","customername2"]
那么直正返回到客户端的是: callbackFunction([“customername1","customername2"])
//服务器返回的这个字符串被嵌入在一个<script> 标签里执行
可能的调用方式:
2. 在客户端写callbackFunction函数的实现
function callbackFunction(result)
{
var html = '<ul>';
for(var i = 0; i < result.length; i++)
{
html += '<li>' + result[i] + '</li>';
}
html += '</ul>';
document.getElementById('divCustomers').innerHTML = html;
}
< / script>
function CallJSONPServer(url){ // 调用JSONP服务器,url为请求服务器地址
var oldScript =document.getElementById(url); // 如果页面中注册了调用的服务器,则重新调用
if(oldScript){
oldScript.setAttribute("src",url);
return;
}
var script =document.createElement("script"); // 如果未注册该服务器,则注册并请求之
script.setAttribute("type", "text/javascript");
script.setAttribute("src",url);
script.setAttribute("id", url);
document.appendChild(script);
}
=======================================================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</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 language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function clickme(){
$.getJSON('http://localhost:8080/web_test/callServer?callback=?',
{number:1},
function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
}
);
}
</script>
</head>
<body>
This is my JSP page.
<br>
<input type="button" value="clickme" onclick="clickme()"></input>
</body>
</html>
jsonp1299753149125({"a": "b","c":"d","e":"f"})
server public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String callback = request.getParameter("callback");
PrintWriter out = response.getWriter();
out.println(callback+"({\"a\": \"b\",\"c\":\"d\",\"e\":\"f\"})");
out.flush();
out.close();
}