Powerful jquery has been supporting JSONP since 1.2, and today we use the servlet to do a little test in the background.
front-end JavaScript (using Jsonpcallback as a callback function, where the success does not work):
function Loadjsonp () {
$.ajax ({
URL: ' http://192.168.28.128:8080/JsonPDemo/servlet/JsonPServlet?callback= Jsonpcallback ',
dataType: "Jsonp",
success:function (data) {
alert (data);
}
);
function Jsonpcallback (data) {
alert (data[0][' name ');
}
Background (get the callback function of the foreground jsonp, Output jsonpcallback (...) ):
public void doget (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
Response.setcontenttype ("text/html");
Response.setcharacterencoding ("Utf-8");
PrintWriter out = Response.getwriter ();
String Jsonp = Request.getparameter ("callback");
String str = "[{' id ': ' 1 ', ' name ': ' Test 1 '},{' id ': ' 2 ', ' name ': ' Test 2 '}]";
str = JSONP + "(" + str + ")";
Out.println (str);
Out.flush ();
Out.close ();
}
Careful friends find that JSONP is not a good technique, he just put the JSON string in the callback function as a parameter in the callback, and then let the front-end call. However, Jsonp is indeed a clever way to address cross-domain access.