您的位置:首页 > Web前端 > JavaScript

JSONP请求简述

2015-11-06 10:34 417 查看

跨域请求-JSONP

原理:通过不受访问限制<script>标签发送请求。

下面做了一个例子,以供参考:

前端代码:

<script type="text/javascript">
//测试jsonp
function handleResponse(data){
Util.log(data);
}
var script = document.createElement("script");
//script.src = "http://freegeoip.net/json/?jsonp=handleResponse";
script.src = "http://localhost:8080/CookieTest/json?callback=handleResponse";
document.body.insertBefore(script,document.body.firstChild);
</script>

后台代码:

request.setCharacterEncoding("UTF-8");

JSONObject json = new JSONObject();

json.put("contentType", request.getContentType());

json.put("contentLength", request.getContentLength());

json.put("contextPath", request.getContextPath());

json.put("remoteAddr", request.getRemoteAddr());

PrintWriter out = response.getWriter();

String callback = request.getParameter("callback");

if(null == callback || "".equalsIgnoreCase(callback)){

    out.print(json);

}else{

    out.print(callback + "(" + json + ");");

}

out.flush();

out.close();

回调函数说明:

其实JSOP回调函数的原理通过上面的例子应该很容易理解,其实后台返回的不是一个json对象,而是将需要返回的json对象作为回调函数的参数进行返回。因为前端是使用<script>标签,加载到的数据会当作js来运行。到这里应该明白jsonp是如何请求数据以及回调函数的原理了吧!!!

注意:若服务器端接口直接返回json对象,则前端无法调用回调函数。

上述为个人理解,理解不到位的地方,望指正!!!

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: