Getting Started with Java EE (XVIII) - Ajax & JSON basis
iwehdio the blog garden: https://www.cnblogs.com/iwehdio/
1、Ajax
Asynchronous JavaScript And XML, Asynchronous JavaScript and XML. Without having to load the entire page to update part of the page.
-
Asynchronous and synchronous:
- Mutual communication client and server end.
- Synchronous means that the client must wait for the server's response, during which the client can not do anything.
- Asynchronous means that the client does not have to wait for the response from the server side, the client can do other operations during this period.
-
Native JS implementation:
-
Binding event function.
<script> function func(){ /* 内容 */ } </script>
-
Create a core object.
var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
-
establish connection.
xmlhttp.open("GET", "text1,txt", true)
. Three parameters are, the type of request and synchronization request URL (false) or asynchronous (true). -
send request.
xmlhttp.send()
. For get embodiment, the parameters to the URL request splicing, send method is empty reference; for the post request, the send request parameter method. -
Receiving a response from the server. Ready status code and the response is a request to complete ready 4, the response status code of 200 indicates a successful response.
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var responseText = xmlhttp.responseText; } }
-
-
JQuery implementations:
$.ajax(url, [settings])
Or$.ajax({键值对})
: to send an asynchronous request. If written in the form of key-value pair, the key comprising a url (parameter request path), type (request mode), Data (request parameter), Success (after a successful callback response), error (the error callback function), dataType (receiving response data format).$.get(url, [data], [callback], [type])
: Send a get request. Parameters were request path, a request parameter, in response to the callback function, and data types.$.post(url, [data], [callback], [type])
: Sending post request.
2、JSON
JavaScript Object Notation, JavaScript Object Notation. A grammar storage or exchange text messages.
-
The basic syntax:
- Data in the name / value pairs: JSON data is composed of key-value pairs. Each pair of key-value pairs separated by commas. Keys can be used without quotation marks can be used, but to be consistent.
- Nested Format: braces definition is stored object definition is stored in an array brackets.
- Save
var v = {"key":{"key1":value1, "key2":value2}}
Object: . - Save
var v = {"key":[{"key1":value1}, {"key2":value2}]}
formula: .
- Save
- The value type of value can play arrays, strings, Boolean values, array, object, or null.
-
retrieve data:
-
json对象.键名
。 -
json对象["键名"]
: Single quotes double quotes can be. -
json数组对象[索引]
。 -
Traversal:
for(var key in json_object){ //在这里key是字符串形式,不能直接 person.key 获取 alert(key + ":" + person[key]); }
-
-
JSON data and converts Java objects: jackson parser.
- Steps for usage:
- Import dependent jar package.
- Creating Jackson core object ObjectMapper.
- Conversion.
- JSON turn Java objects:
mapper.readValue(JSON字符串数组, class类型)
: Class type is to be converted into a class object.
- Java objects turn JSON:
mapper.writeValueAsString(obj)
: Java objects into JSON string.mapper.writeValue(参数,obj)
: Java objects into JSON string, and stored in a file (File object parameter), character-output stream (parameter Writer object), byte output stream (OutputStream object parameter).- annotation:
@JsonIgnore
: Ignore this property, this property does not appear when turn JSON. Applied to the member variable.@JsonFormat(格式)
: Format property value. Applied to the member variable. As described for Date, the format may bepattern = "yyy-MM-dd"
.
- Complex Java objects:
- List array: into a JSON array.
- Map Collection: convert a JSON object.
- Steps for usage:
3, case
-
Validate the user name exists:
-
User name to the server through a browser, the server, after determining, in response to the browser implemented JSON data.
-
login.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JSON</title> <script src="js/jquery-3.3.1.min.js"></script> <script> $(function () { $("#username").blur(function () { var username = $(this).val(); $.get("findUsernameServlet", {username:username}, function (data) { var span = $("#tips"); if(data.userExist){ span.css("color", "red"); span.html(data.msg); } else { span.css("color", "green"); span.html(data.msg); } }, "json") }) }) </script> </head> <body> <form> <input type="text" name="username" id="username" placeholder="请输入用户名"><br> <span id="tips"></span> </form> </body> </html>
-
FindUsernameServlet:
@WebServlet("/findUsernameServlet") public class FindUsernameServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); Map<String, Object> map = new HashMap<String, Object>(); //此处应使用数据库查询 if("otto".equals(username)){ map.put("userExist", true); map.put("msg", "用户名已被占用"); } else { map.put("userExist", false); map.put("msg", "用户名可以使用"); } ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getWriter(), map); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
-
Learn how to make the browser the response is JSON types of data, prevent garbled:
- In
$.get()
designated as "json" The last type parameter method. - In
response.setContentType("application/json;charset=utf-8")
specifying the MIME type as json.
- In
-
iwehdio Park's blog: [https://www.cnblogs.com/iwehdio/] (https://www.cnblogs.com/iwehdio/)