Brief analysis and practical operation of Ajax

一个新手
Release: 2017-09-09 10:39:47
Original
1264 people have browsed it

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 thetag Just some configuration items, readers can copy them by themselves)

  XHR   
 

Copy after login

Page running effect
Brief analysis and practical operation of Ajax
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 usingvar form = document.getElementById('form')to obtain the form form node, we can directly useform.nickorform[nick]To directly obtain the nickname input box node, of course, the premise is that the element in the form form has thenameattribute 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); }
Copy after login

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 usevar 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.onreadystatechangeThe stage in which the monitoring request response process is implemented. Mainly through thereadyStateattribute 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}: ''));
Copy after login

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:


Brief analysis and practical operation of Ajax

四、发送请求

xhr.send(type === 'get' ? null : data);最后一个环节,上面说到的post传参就要在这传入,get则不用,所以在这里同样用了一个三目运算。
Copy after login

基本上,原生的XHR对象实现ajax请求就如上所说;是不是觉得有点复杂?那么不用慌,喜欢“偷懒”的高端程序猿已经帮我们实现了封装;没错就是当初影响世界的jQuery。话不多说,直接上代码:

$.ajax(function() { url: 'xhr', type: 'get', dataType: 'json',//返回数据类型 data: {info: data},//传参 success: function(data) { /***/ }, error: function() { console.log('error!'); } });
Copy after login

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 map = new HashMap(); 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"; } }
Copy after login

struts.xml

     info    
Copy after login

在这里只强调一点,struts2的自动打包传值,一定要保证参数名一致!即你在前台封装json数据格式时,对应的key值要和struts.xml配置文件中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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!