AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是一种用于建立快速动态网页的手艺。
动态网页:是指可以经由过程办事器说话连系数据库随时点窜数据的网页。
静态网页,跟着html代码的生当作,页面的内容和显示结果就根基上不会发生转变了——除非你点窜页面代码。
AJAX = 异步 JavaScript和XML(尺度通用标识表记标帜说话的子集)。
AJAX 是与办事器互换数据并更新部门网页的艺术,在不从头加载整个页面的环境下。
第一种:建立一个springboot的项目。
1、 打开建立页面 选择File-new-project..
2、选择建立的项目为spring initializr 进入springboot项目建立步调(也可以选择类型java,建立一个通俗java项目)
3、输入项目名字,选择依靠web(按照项目需求选择,此次需要),选择存放目次-完当作(Finish)
4、pom.xml中添加html视图依靠:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
第二种:建立一个简单的javaweb项目。
1、直接打开:https://jingyan.baidu.com/article/ff411625048acf12e482373a.html
2、或者百度搜刮:servlet类若何映射到url路径 百度经验
第一步:编写一个controller。
本家儿如果两个方式跳转页面ajax_js.html和返回ajax请求数据
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@Controller
public class TestController {
@RequestMapping("/toAjax")
String test(HttpServletRequest request) {
return "ajax_js";
}
@ResponseBody
@RequestMapping("/bean")
public String testJson(HttpServletRequest request,
HttpServletResponse response, Map paramMap) {
String callback = request.getParameter("callback");
String id = request.getParameter("id");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String json = "{'id':" + id + ",'name':'" + name + "','sex':'" + sex
+ "'}";
if (callback != null) {
json = callback + "(" + json + ")";
}
return json;
}
}
第二步:前端页面js原生挪用get体例的实现。
1、具体前端页面代码如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//参数1:请求体例 参数2:请求地址 参数3:是否异步 true暗示异步,false暗示同步
xmlHttp.open('GET', '/bean?id=2&name=张三&sex=男', true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
};
</script>
</body>
</html>
2、测试输入浏览器页面地址
http://localhost:8080/toAjax
第三步:前端页面js原生挪用post体例的实现。
1、前端页面如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//参数1:请求体例 参数2:请求地址 参数3:是否异步 true暗示异步,false暗示同步
xmlHttp.open('POST', '/bean', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send('id=2&name=张三&sex=男');
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
};
</script>
</body>
</html>
2、测试
2.1 在浏览器中输入地址 http://localhost:8080/toAjax跳转到ajax请求页面
0 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!