Detailed Jquery and AngularJs, Servlet in jsonp solve cross-domain problems (rpm)

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);
}
  1. 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.
  2. When the request for the data type jsonp, will be added to the callback = jsonpCallback url, http: // localhost: 8090 / api / testcallback = jsonpCallback
  3. Reception defined jsonpCallback javascript function, which must be defined in the window, which is a global function, or can not be found.
  4. Get background jsonpCallback callback request parameter values, return the string "jsonpCallback (result)", result returns a result.
  5. Request the return of script tag, first calls jsonpCallback function, regardless of whether the find function, the function will be called success.
  6. 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);
  }
); 
  1. angularJS used $ http.jsonp function
  2. Specifies the callback and the callback function name, a function called JSON_CALLBACK, calls the success callback, JSON_CALLBACK must be all uppercase.
  3. You can also specify other callback function, but must be defined in the window of global functions.
  4. url must add callback
  5. 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

Guess you like

Origin blog.csdn.net/weixin_33716557/article/details/93057306
Recommended