jsonp Cross Domain Request Implementation Sample

  • 2021-08-03 08:52:57
  • OfStack

I read a lot of information about jsonp on the Internet, and found that it can't be realized after running this machine. Some of them have mistakes and omissions, and some of them are vague. I combined my own situation and made a running example;

Foreword:

ajax Request Address: http://192.168. 1.102: 8080/carop/jsonp

jsonp string to be returned by the server: jsonpCallback ({"name": "Andy Lau", "Phone": "1768888888"})

The writing of jsonp can be understood as the execution of an javascript function. For example, alert ("hello world") will pop up the window of hello world, and alert ({"name": "Andy Lau}) will pop up the window of [object Object]. (Note that there are no double quotation marks at both ends of the parameter. It is an object with attributes instead of a string.)

Then in jsonp of this example, jsonpCallback can be understood as the function name, and the object {"name": "Andy Lau", "Phone": "1768888888"} is the parameter to be passed when this function is executed.

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, can also be written differently, and only one method is used here.

Explanation: jsonpCallback: "jsonpCallback", the first ajax parameter indicates the function to be executed, and the latter "jsonpCallback", which is the javascript function name returned by the server to jsonp. (There are relevant information on the Internet. This parameter is written as jsonp instead of jsonpCallback. After actual test, it should be written as jsonpCallback and jquery version 1.8. The tested browsers are Firefox and edge)

Server side

The servlet controller layer directly returns to jsonp;


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);
 }
}

Related articles: