Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Ajax's data type


May 30, 2021 Article blog


Table of contents


In the use of Ajax, there is a problem: the interface was developed for use on mobile phones, but the data is provided through the server API, in bounds

The face uses JQuery's Ajax to call the data, can't start to call, and doesn't report problems, and now the browser is tested to load the local interface on the phone.

1, the server key code below:

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

*      response)

*/

protected void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

Response.setContentType ("text / javascript"); // should pay attention to

PrintWriter out = response.getWriter();

String callback = request.getParameter("callback");

out.print(callback

+ "([{ name:'John',age:'19'},{ name:'joe',age:'20'}])");

System.out.println("callback = " + callback);

out.flush();

out.close();

}

2, interface key code:

$.ajax({

url:"http://localhost:8081/JsonpServer/JsonpServlet",

dataType:"jsonp",

Jsonp: "Callback", // Pass to request the handler or page to obtain the parameter name of the JSONP callback function (the default is: callback), which needs to be consistent with the server.

JsonpCallback: "person", // Custom JSONP callback function name, acquiescence the random function name automatically generated by jQuery

success:function(json){

//alert(json[0].name);

}

});

// Equipped with functions performed after rewriting Success (custom as Person)

function person(json){

alert("I am person function...");

alert(json[0].name);

}

analyse:

The initial effect was dataType: "json", so the test did not come out for a long time, and was later modified to dataType: "jsonp", which could be used.
The reason is that when dataType is a json data format, it cannot be accessed across domains, and jsonp is accessed across domains.


The following lessons can help you get a better understanding of XML: