As we all know, jsonp can solve the problem of cross-domain, here are some of my summary on access to information and use of the actual project.
Jquery use in jsonp
//myUrl = "http://localhost:8090/api/test"; $.ajax({ type:"GET", url:myUrl, dataType:"jsonp", jsonp:"callback", jsonpCallback:"jsonpCallback", success:function(data){ alert(data.msg); } }); function jsonpCallback(data){ alert(data); }
- jsonp use only get a request to address the problem of homologous returns javascript code because the request javascript file is not homologous to the problem.
- When the request for the data type jsonp, will be added to the callback = jsonpCallback url, http: // localhost: 8090 / api / testcallback = jsonpCallback
- Reception defined jsonpCallback javascript function, which must be defined in the window, which is a global function, or can not be found.
- Get background jsonpCallback callback request parameter values, return the string "jsonpCallback (result)", result returns a result.
- Request the return of script tag, first calls jsonpCallback function, regardless of whether the find function, the function will be called success.
- If not defined jsonp and jsonpCallback, jsonp default "callback", jsonpCallback will be automatically generated Jquery function name.
angularJS use in jsonp
myUrl = "http://localhost:8090/api/testcallback=JSON_CALLBACK"; $http.jsonp(myUrl).success( function(data){ alert(data); } );
- angularJS used $ http.jsonp function
- Specifies the callback and the callback function name, a function called JSON_CALLBACK, calls the success callback, JSON_CALLBACK must be all uppercase.
- You can also specify other callback function, but must be defined in the window of global functions.
- url must add callback
- When the callback is JSON_CALLBACK, just call success, even if the window has JSON_CALLBACK function, it will not call the function.
The use of Servlet
@Override protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ resp.setContentType("application/json;charset=UTF-8"); PrintWriterout=resp.getWriter(); StringcallbackFunName=req.getParameter("callback"); StringBuilderstringBuilder=newStringBuilder(callbackFunName); stringBuilder.append("("); stringBuilder.append(123); stringBuilder.append(")"); out.println(stringBuilder.toString()); out.print(result); out.flush(); out.close(); }
转载于:https://www.cnblogs.com/JoannaQ/p/3712911.html