jsonp(json with padding)是资料格式 json 的一种“使用模式”,可以让网页从别的网域获取资料。
一. 客户端
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
<script type="text/javascript" src="resource/js/jquery-1.7.2.js"></script>
</head>
<script type="text/javascript">
$(function(){
/*
//简写形式,效果相同
$.getjson("http://app.example.com/base/json.do?sid=1494&busiid=101&jsonpcallback=?",
function(data){
$("#showcontent").text("result:"+data.result)
});
*/
$.ajax({
type : "get",
async:false,
url : "http://app.example.com/base/json.do?sid=1494&busiid=101",
datatype : "jsonp",//数据类型为jsonp
jsonp: "jsonpcallback",//服务端用于接收callback调用的function名的参数
success : function(data){
$("#showcontent").text("result:"+data.result)
},
error:function(){
alert('fail');
}
});
});
</script>
<body>
<p id="showcontent">result:</p>
</body>
</html>
二. 服务器端
import java.io.ioexception;
import java.io.printwriter;
import java.util.hashmap;
import java.util.map;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import net.sf.json.jsonobject;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
@controller
public class exchangejsoncontroller {
@requestmapping("/base/json.do")
public void exchangejson(httpservletrequest request,httpservletresponse response) {
try {
response.setcontenttype("text/plain");
response.setheader("pragma", "no-cache");
response.setheader("cache-control", "no-cache");
response.setdateheader("expires", 0);
map<string,string> map = new hashmap<string,string>();
map.put("result", "content");
printwriter out = response.getwriter();
jsonobject resultjson = jsonobject.fromobject(map); //根据需要拼装json
string jsonpcallback = request.getparameter("jsonpcallback");//客户端请求参数
out.println(jsonpcallback+"("+resultjson.tostring(1,1)+")");//返回jsonp格式数据
out.flush();
out.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
以上就是简单了解jquery+ajax+jsonp 跨域访问 的详细内容。