Online read a lot of information about JSONP, found in the machine after the implementation can not, some have errors, some say the more vague, bonded their own situation, the whole of a running example;
Objective:
Ajax Request Address: Http://192.168.1.102:8080/carop/jsonp
Jsonp string to be returned by the server: Jsonpcallback ({"Name": "Andy Lau", "Phone": "17688888888"})
JSONP notation can be interpreted as a JavaScript function execution, such as alert ("Hello World") will pop up the window of Hello World, such as alert ({"Name": "Andy Lau"}) will pop up [object Object] window. (Note that there are no double quotes at both ends of the argument, it is an object with attributes and not a string)
In the JSONP of this example, Jsonpcallback can be understood as the function name {"Name": "Andy Lau", "Phone": "17688888888"} This object is the parameter to pass when the function executes.
Client:
$.ajax ({
type: "Get",
Async:false,
URL: "Http://192.168.1.102:8080/carop/jsonp",
dataType: "Jsonp",
jsonpcallback: "Jsonpcallback",
success:function (data) {
alert (data.name+ "\ n" +data.tel);
}
});
Other Ajax methods, such as Getjson, differ in wording, and only one method is used here.
Description: Jsonpcallback: "Jsonpcallback", the previous Ajax parameter represents the function to be executed, followed by "Jsonpcallback", this is the JavaScript function name that the server returns JSONP. (There is information on the Internet This parameter is written JSONP instead of Jsonpcallback, the actual test to write Jsonpcallback,jquery version 1.8, the test browser for Firefox and Edge)
Service side
The servlet controller layer returns JSONP directly;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
@WebServlet ("/jsonp")
public class Jsonp extends httpservlet{
@Override
protected void doget ( HttpServletRequest req, HttpServletResponse resp)
throws servletexception, IOException {
Resp.setcharacterencoding ("UTF-8");
//system.out.println ("Enter Jsonp");
resp.setcontenttype ("Text/json;charset=utf-8");
string json= "{\" Name\ ": \" Andy lau \ ", \" tel\ ": \" 17688888888\ "}";
string jsonp= "Jsonpcallback (" +json+ ")";
printwriter Pw=resp.getwriter ();
system.out.println (JSONP);
pw.print (JSONP);
}
@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
throws servletexception, IOException {
//TODO auto-generated method stub
doget ( req, resp);
}
}
JSONP Cross-domain Request implementation Example