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对象,则前端无法调用回调函数。

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

你可能感兴趣的:(跨域请求,json请求,jsop)