Those words at the beginning
Purpose
First of all, I am a information manager, and I studied SSH framework background java development as an undergraduate (I learned it in a mess). Usually when developing web projects, JSP is used to directly display the page, and then various forms are submitted and actions jump. As a result, once the data needs to be updated, the page must be refreshed, even in a small part. This is very troublesome and affects the user experience. I have always wanted to use a technology to solve this problem. So I fiddled with it in private for a while, looked at ajax, and found that struts2 perfectly supports ajax, so I wrote this article for reference for people who have had the same story as me! (ps: I usually have classmates ask me about it privately at work, so I just sorted it out for reference!)
Preparation in advance
This article mainly talks about ajax applications in the struts2 environment. . So you need to import all related jar packages of struts2 into your Web project in advance. Anyone who has studied this knows that, so I won’t go into details here; in addition, you need to import an additional jar package to support the json data format. ;I will send the jar package as an attachment. Basically, once you’ve done this, you’re ready to start!
Specific implementation
I will talk about two examples specifically, one is used to describe the specific process of ajax request, and the other is related to the actual application-returning the corresponding according to the parameters data.
Page code (HTML+CSS+JS)
Post code 1 first (for convenience, I did not post the jsp code, in fact, it is just the tag Just some configuration items, readers can copy them by themselves)
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <title>XHR</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <style> form, .box { margin: 50px; padding: 20px; } form p { margin: 20px 0; } .box { background-color: rgba(0, 0, 0, 0.2); height: 40px; width: 300px; } </style></head><body> <form id="form"> <p><label for="nick">昵称:</label> <input value="jero" name="nick" id="nick" type="text" required></p> <p><label for="love">爱好:</label> <input value="coding" name="love" id="love" type="text" required></p> <p> <button type="button" name="get">Get 提交</button> <button type="button" name="post">Post 提交</button> </p> </form> <p id="box" class="box"></p> <script> var byId = (id) => document.getElementById(id); // ES6 箭头函数 var form = byId('form'); var box = byId('box'); /** * 表单的数据收集起来 */ function getData(type) { var result = []; var isFill = false; // 都是文本框的 name ['nick', 'love'].forEach((fieldName) => { var v = form[fieldName].value; var obj = {}; if (v) { obj[fieldName] = v; result.push(obj); isFill = true; } else { isFill = false; } }); if (!isFill) { // 没填的话要返回没填的结果 false return false; } result = JSON.stringify(result); result = "info" + '=' + encodeURIComponent(result) return result; } function request(type, callback) { var data = getData(type); if (!data) { // 没填的话直接警告 return alert("完成表单!"); } var xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { callback(JSON.parse(xhr.responseText), xhr); } else { console.log(xhr.status); } } xhr.open(type, './xhr' + (type === 'get' ? `?${data}` : '')); // get 的参数直接拼在 url 的末尾 // 模拟 post 请求,必须设置个请求头 if (type === 'post') { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')//可以自己根据实际情况改变取值 } xhr.send(type === 'get' ? null : data); } /** * 绑定事件抽象下 */ function click(btn, callback) { btn.addEventListener('click', () => { request(btn.name, (data) => { var data = JSON.parse(data); box.innerHTML = `success by ${data[0].type} method!<br> ${data[0].infoStr}`; console.log(data); }); }); } // 绑定事件,代码可以从这里看 click(form.get); click(form.post) </script></body></html>
Page running effect
There are several points in the above code that I will talk about here. 1.encodeURIComponent()
This function is used to convert variables into strings in url addresses to avoid garbled characters when passing values. 2. When using var form = document.getElementById('form')
to obtain the form form node, we can directly use form.nick
or form[nick]
To directly obtain the nickname input box node, of course, the premise is that the element in the form form has the name
attribute set.
Then let’s focus on interpreting this code:
function request(type, callback) { var data = getData(type);//参数列表字符串 if (!data) { // 没填的话直接警告 return alert('完成表单!'); } var xhr = new XMLHttpRequest();//生成XHR对象 xhr.onreadystatechange = () => { if (xhr.readyState === 4) { callback(JSON.parse(xhr.responseText), xhr);//数据成功接收后的回调函数 } else { console.log(xhr.status); } } xhr.open(type, './xhr' + (type === 'get' ? `?${data}` : '')); // get 的参数直接拼在 url 的末尾 // 模拟 post 请求,必须设置个请求头 if (type === 'post') { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')//可以自己根据实际情况改变取值 } xhr.send(type === 'get' ? null : data); }
First of all, let’s make it clear that the function of this function is to send an ajax request; here I use the native XHR object to implement the ajax request, the purpose is to let everyone Be able to deeply understand what ajax is all about; generally speaking, sending an ajax request is divided into four steps:
1. Create an XHR object
IE7 and above and now mainstream browsers support it Native XHR object, so we can directly use var xhr = new XMLHttpRequest();
to create an XHR object, and use some methods encapsulated by the XHR object to implement ajax requests. As for the cancer below IE7, I will never consider it! If you insist on making it compatible with IE7 or below, you can refer to the ajax chapter of the js red book. It is created through ActiveX objects!
2. Bind the listening function
xhr.onreadystatechange
The stage in which the monitoring request response process is implemented. Mainly through the readyState
attribute of the Call send() method)
2-Send (call send() method, but no response, no data received)
3-Receive (partial data received)
4-Complete (get all Response data)
Whenever the attribute value changes, a readystatechange event is triggered. So we can use the value of this attribute to determine whether the data we need is ready. In order to render the data we requested into the page in a timely manner.
And
xhr.status
returns the status code of the HTTP request (students who have studied networking should all know this), which makes it easier for us to detect whether the request is successful, or to determine the reason for the request failure. callback(JSON.parse(xhr.responseText), xhr);
This is the callback function to be executed when we receive all the data. It is mainly used to process the received data and render the page. You can follow it in actual application. The focus is on writing the callback function in the binding function. You should write it according to actual needs. 3. Start the request
xhr.open(type, './xhr' + (type === 'get' ??${data}: ''));
The first parameter mainly sets whether the request uses the get method or the post method. (ps: A recent article said that there is no difference between the two. Here we For now, follow the old routine), and the second one is the target address of the request. A ternary operation is used to distinguish get and post. Because the parameters of the get method are sent to the background by putting the parameters in the url, so we have to Concatenate strings; and post is passed through the Form Data in the request header; as shown below:
四、发送请求
xhr.send(type === 'get' ? null : data);最后一个环节,上面说到的post传参就要在这传入,get则不用,所以在这里同样用了一个三目运算。
基本上,原生的XHR对象实现ajax请求就如上所说;是不是觉得有点复杂?那么不用慌,喜欢“偷懒”的高端程序猿已经帮我们实现了封装;没错就是当初影响世界的jQuery。话不多说,直接上代码:
$.ajax(function() { url: 'xhr', type: 'get', dataType: 'json',//返回数据类型 data: {info: data},//传参 success: function(data) { /***/ }, error: function() { console.log('error!'); } });
jQuery提供了很多种写法,包括更简单的$.getJSON()
;至于我为什么要推荐这种写法,大家可以理解成我很笨,但是其中的含义大家用过就明白了!(吹个小牛皮)
后台代码(action+struts.xml)
上面说了这么多,一是让大家了解原生的是怎样的一个东西,二是因为上述部分是学习后台同学没有接触过的,所以尽可能的讲清楚点;这部分,我想代码一贴出来,大家都懂了!
action
package com.testforajax.demo.action;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import org.apache.struts2.ServletActionContext;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import com.opensymphony.xwork2.ActionSupport;public class AjaxDemo extends ActionSupport { private String info; public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String execute() throws Exception { String method = ServletActionContext.getRequest().getMethod(); HashMap<String, String> map = new HashMap<String, String>(); String name; String love; JSONArray json = JSONArray.fromObject(info); name = json.getJSONObject(0).getString("nick"); love = json.getJSONObject(1).getString("love"); json.clear(); String result = name + " very love " + love; map.put("type", method); map.put("infoStr", result); json.add(map); info = json.toString(); System.out.println(this.info); return "success"; } }
struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts> <!-- XHR演示 --> <package name="xhrTest" extends="json-default, struts-default"> <action name="xhr" class="com.testforajax.demo.action.AjaxDemo"> <result type="json"> <param name="root">info</param> </result> </action> <!-- <action name="newxhr" class="com.testforajax.demo.action.AjaxDemo2"> <result type="json"> <param name="root">queryId</param> </result> </action> --> </package></struts>
在这里只强调一点,struts2的自动打包传值,一定要保证参数名一致!即你在前台封装json数据格式时,对应的key值要和struts.xml配置文件中<param name="root">info
一致,同时在action类中也要有对应的属性,以及getter和setter。
还有,在使用json数据格式时要做到传参时记得JSON.stringify()
,渲染响应数据时记得JSON.parse()
。封装时,一定要按照标准格式,后台封装的话,推荐我写的那种先用map做处理。
The above is the detailed content of Brief analysis and practical operation of Ajax. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools