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 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!