JSONP请求简述
跨域请求-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对象,则前端无法调用回调函数。
上述为个人理解,理解不到位的地方,望指正!!!
阅读更多- struts2 在result type = json 时 ,兼容json与jsonp 请求
- FlyJSONP——实现跨域Get & Post请求
- JSONP的跨域请求
- jsonp跨域请求
- 浅谈JSONP跨域请求
- PHP AJAX JSONP实现跨域请求使用实例
- AJAX 跨域请求 - JSONP获取JSON数据
- JSONP跨域请求
- 用jsonp解决ajax跨域请求
- JSONP:(发js请求)请求script,返回回调函数
- jsonp跨域请求
- AJAX跨域请求之JSONP
- jsonp不同的请求方式
- 使用jsonp进行跨域请求数据
- Spring Boot支持JSONP跨域请求数据(Ajax的jsonp)
- 使用jquery的jsonp如何发起跨域请求及其原理详解
- 点击<a>页面跳转解决办法/跨域请求,JSONP
- jsonp解决跨域请求问题
- Jquery之AJAX COOKIES跨域请求 - JSONP实现方法
- 通过jsonp解决ajax的跨域请求问题