Web數(shù)據(jù)交互方式,Ajax:
Ajax,Asynchronous Javascript And XML(異步JavaScript和XML),2005年被Jesse James Garrett提出的新術(shù)語(yǔ),用來(lái)描述一種使用現(xiàn)有技術(shù)集合的新方法,包括:HTML或XHTML,CSS,JavaScript,DOM,XML,XSLT,以及最重要的XMLHttpRequest。 使用Ajax技術(shù)網(wǎng)頁(yè)應(yīng)用能夠快速地將增量更新呈現(xiàn)在用戶界面上,而不需要重載(刷新)整個(gè)頁(yè)面,這使得程序能夠更快地回應(yīng)用戶的操作。
jQuery
jQuery是一個(gè)快速、簡(jiǎn)潔的JavaScript框架,是繼Prototype之后又一個(gè)優(yōu)秀的JavaScript代碼庫(kù)(框架)于2006年1月由John Resig發(fā)布。封裝了JavaScript常用的功能代碼,提供一種簡(jiǎn)便的JavaScript設(shè)計(jì)模式,優(yōu)化HTML文檔操作、事件處理、動(dòng)畫(huà)設(shè)計(jì)和Ajax交互。
Axios
一個(gè)基于promise的HTTP庫(kù),可以用在瀏覽器和node.js中。
跨域資源共享(CORS)
CORS是一個(gè)W3C標(biāo)準(zhǔn),全稱是"跨域資源共享"(Cross-origin resource sharing)。允許瀏覽器向跨源服務(wù)器,發(fā)出XMLHttpRequest請(qǐng)求,從而克服了AJAX只能同源使用的限制。
原生的Ajax同步&異步代碼案例
//Ajax Get 同步請(qǐng)求
function AjaxSynGet(url) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
//IE
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// xmlHttp.setRequestHeader("headName", "headName");
xmlHttp.open("GET", url + '&rnd=' + Math.random(), false);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.send(null);
var text=xmlHttp.responseText;
return text;
}
//Ajax Post 同步請(qǐng)求
function AjaxSynPost(url, param) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
//IE
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("POST", url + '&rnd=' + Math.random(), false);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.setRequestHeader("headName", 'headValue');
xmlHttp.send(param);
var text=xmlHttp.responseText;
return text;
}
//Ajax Get 異步請(qǐng)求
// rtnFun: 函數(shù)
function AjaxGet(url, rtnFun) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
//IE
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp !=null) {
//get
xmlHttp.open("GET", url + '&rnd=' + Math.random(), true);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.send(null);
xmlHttp.onreadystatechange=function() {
//4="loaded"
if (xmlHttp.readyState==4) {
//200=OK
if (xmlHttp.status==200) {
var text=xmlHttp.responseText;
rtnFun(text);
}
}
}
}
}
//Ajax Post 異步請(qǐng)求
// rtnFun: 函數(shù)
function AjaxPost(url, param, rtnFun) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
//IE
} else if (window.ActiveXObject) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp !=null) {
xmlHttp.open("POST", url + '&rnd=' + Math.random(), true);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.setRequestHeader("headName", 'headValue');
xmlHttp.send(param);
xmlHttp.onreadystatechange=function() {
//4="loaded"
if (xmlHttp.readyState==4) {
//200=OK
if (xmlHttp.status==200) {
var text=xmlHttp.responseText;
rtnFun(text);
}
}
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生的Ajax同步&異步代碼案例</title>
<!--r為參數(shù)防止瀏覽器緩存 -->
<script type="text/javascript" src="ajax.js?r=2"></script>
</head>
<body>
<div>
<span id="result1"></span>
<hr/>
<span id="result2"></span>
<hr/>
<span id="result3"></span>
<hr/>
<span id="result4"></span>
</div>
<script type="text/javascript">
// 1、Ajax Get同步請(qǐng)求
let result1=AjaxSynGet("http://192.168.1.116:8080/data/get?a=1");
console.log("result1",result1);
document.getElementById("result1").innerText=result1;
// 2、Ajax Post 同步請(qǐng)求
let result2=AjaxSynPost("http://192.168.1.116:8080/data/post?a=1","key=value");
console.log("result2",result2);
document.getElementById("result2").innerText=result2;
// 3、Ajax Get 異步請(qǐng)求
console.log("請(qǐng)求前:" + new Date().getTime());
AjaxGet("http://192.168.1.116:8080/data/get?a=1", function(data){
console.log("result3",data);
document.getElementById("result3").innerText=data;
});
console.log("請(qǐng)求后:" + new Date().getTime());
// 4、Ajax Ajax Post 異步請(qǐng)求
console.log("請(qǐng)求前:" + new Date().getTime());
AjaxPost("http://192.168.1.116:8080/data/post?a=1", "key=value", function(data){
console.log("result4",data);
document.getElementById("result4").innerText=data;
});
console.log("請(qǐng)求后:" + new Date().getTime());
</script>
</body>
</html>
jQuery的Ajax同步&異步代碼案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery的Ajax同步&異步代碼案例</title>
<script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div>
<span id="result1"></span>
<hr/>
<span id="result2"></span>
<hr/>
<span id="result31"></span>
<hr/>
<span id="result32"></span>
<hr/>
<span id="result41"></span>
<hr/>
<span id="result42"></span>
</div>
<script type="text/javascript">
// 1、Ajax Get同步請(qǐng)求
let result1=$.ajax({
type: 'get',
url: 'http://192.168.1.116:8080/data/get',
async:false,
headers:{'token':'1333333333'},
});
console.log("result1",result1.responseText);
$("#result1").text(result1.responseText);
// 2、Ajax Post 同步請(qǐng)求
let result2=$.ajax({
type: 'post',
url: 'http://192.168.1.116:8080/data/post',
data: {},
async:false,
headers:{'token':'1333333333'},
});
console.log("result2",result2.responseText);
$("#result2").text(result2.responseText);
// 3、Ajax Get 異步請(qǐng)求
$.get("http://192.168.1.116:8080/data/get", function(data,status){
console.log("result31", JSON.stringify(data));
$("#result31").text(JSON.stringify(data));
});
$.ajax({
type: 'get',
url: 'http://192.168.1.116:8080/data/get',
async: true,
headers:{'token':'1333333333'},
success: function (res){
console.log("result32", JSON.stringify(res));
$("#result32").text(JSON.stringify(res));
},
error:function(err){
console.log("error32", err);
}
});
// 4、Ajax AjaxPost 異步請(qǐng)求
$.post("http://192.168.1.116:8080/data/post",{ id:''},function(data){
console.log("result41", JSON.stringify(data));
$("#result41").text(JSON.stringify(data));
});
$.ajax({
type: 'post',
url: 'http://192.168.1.116:8080/data/post',
data:{ id:'' },
contentType: 'application/x-www-form-urlencoded',
async: false,
headers:{'token':'1333333333'},
success: function (res){
console.log("result42", JSON.stringify(res));
$("#result42").text(JSON.stringify(res));
},
error:function(err){
console.log("error42", err);
}
});
</script>
</body>
</html>
Axios的Ajax同步&異步代碼案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Axios的Ajax同步&異步代碼案例</title>
<script src="https://lib.baomitu.com/axios/0.21.4/axios.min.js"></script>
</head>
<body>
<div>
<span id="result11"></span>
<hr/>
<span id="result12"></span>
<hr/>
<span id="result21"></span>
<hr/>
<span id="result22"></span>
<hr/>
<span id="result31"></span>
</div>
<script type="text/javascript">
// URL編碼 URL解碼
console.log("URL編碼",encodeURIComponent("名字"));
console.log("URL解碼",decodeURIComponent("%E5%90%8D%E5%AD%97"));
// 1、Ajax Get異步請(qǐng)求
axios.get('http://192.168.1.116:8080/data/get?id=11&name=名字',{
params: {desc:"描述"},
headers: {"token": "token123"}
}).then(res=> {
console.log("result11", JSON.stringify(res.data));
document.getElementById("result11").innerText=JSON.stringify(res.data);
});
// 另外一種寫(xiě)法
axios({
url: 'http://192.168.1.116:8080/data/get?id=12&name=名字',
method: 'GET',
params: {desc:"描述"},
headers: {"token": "token123"}
}).then(res=> {
console.log("result12", JSON.stringify(res.data));
document.getElementById("result12").innerText=JSON.stringify(res.data);
})
// 2、Ajax Post異步請(qǐng)求
axios.post('http://192.168.1.116:8080/data/post',"id=21&name=名字",{
headers: {"token": "token123"}
}).then(res=> {
console.log("result21", JSON.stringify(res.data));
document.getElementById("result21").innerText=JSON.stringify(res.data);
})
// 另外一種寫(xiě)法
axios({
url: 'http://192.168.1.116:8080/data/post',
method: 'post',
data: {id: 22,name:'名字'},
headers: {"token": "token123"}
}).then(res=> {
console.log("result22", JSON.stringify(res.data));
document.getElementById("result22").innerText=JSON.stringify(res.data);
});
// 3、Ajax Get同步請(qǐng)求
console.log("請(qǐng)求前:" + new Date().getTime());
async function getData() {
let data="";
await axios.get('http://192.168.1.116:8080/data/get?id=31&name=名字').then(res=> {
data=JSON.stringify(res.data);
console.log("執(zhí)行1:" + new Date().getTime());
});
console.log("執(zhí)行2:" + new Date().getTime());
return data;
}
const result=getData();
result.then(res=>{
console.log("執(zhí)行3:" + new Date().getTime());
console.log("result31", res);
document.getElementById("result31").innerText=res;
})
console.log("請(qǐng)求后:" + new Date().getTime());
</script>
</body>
</html>
SpringBoot后臺(tái)代碼
跨域的Filter:
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response=(HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
//response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
response.setHeader("Access-Control-Allow-Headers", "*");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
配置(主要是跨域):
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CommonConfig {
@Bean
public FilterRegistrationBean registerAuthFilter() {
FilterRegistrationBean registration=new FilterRegistrationBean();
registration.setFilter(new SimpleCORSFilter());
registration.addUrlPatterns("/*");
registration.setName("simpleCORSFilter");
registration.setOrder(1); // 值越小,F(xiàn)ilter越靠前。
return registration;
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration=new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允許任何域名
corsConfiguration.addAllowedHeader("*"); //允許任何頭
corsConfiguration.addAllowedMethod("*"); //允許任何方法
return corsConfiguration;
}
// @Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //注冊(cè)
return new CorsFilter(source);
}
}
Controller支持:
.Net core中,當(dāng)使用ajax提交json數(shù)據(jù)時(shí),因?yàn)樵?net core中是屬于強(qiáng)類型數(shù)據(jù),所以在數(shù)據(jù)接受時(shí)可以使用[FromBody]標(biāo)簽采用自定義注冊(cè)的方法,其代碼參考如下(以下代碼原文出處:https://www.cnblogs.com/showmu/p/6264950.html):
public class JObjectModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context==null) throw new ArgumentNullException(nameof(context));
if (context.Metadata.ModelType==(typeof(JObject)))
{
return new JObjectModelBinder(context.Metadata.ModelType);
}
return null;
}
}
public class JObjectModelBinder : IModelBinder
{
public JObjectModelBinder(Type type)
{
if (type==null)
{
throw new ArgumentNullException("type");
}
}
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext==null) throw new ArgumentNullException("bindingContext");
ValueProviderResult result=bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
try
{
JObject obj=new JObject();
if (bindingContext.ModelType==typeof(JObject))
{
foreach (var item in bindingContext.ActionContext.HttpContext.Request.Form)
{
obj.Add(new JProperty(item.Key.ToString(), item.Value.ToString()));
}
if ((obj.Count==0))
{
bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(result.ToString()));
return Task.CompletedTask;
}
bindingContext.Result=(ModelBindingResult.Success(obj));
return Task.CompletedTask;
}
return Task.CompletedTask;
}
catch (Exception exception)
{
if (!(exception is FormatException) && (exception.InnerException !=null))
{
exception=ExceptionDispatchInfo.Capture(exception.InnerException).SourceException;
}
bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, exception, bindingContext.ModelMetadata);
return Task.CompletedTask;
}
}
}
在start.cs中configure添加注冊(cè)
services.AddMvc(options=>
{
options.ModelBinderProviders.Insert(0, new JObjectModelBinderProvider());//加入JobjectModelBinderProvider綁定
});
在后臺(tái)接受是如下
[HttpPost]
public stringLogin([FromBody]JObject data)
{
return "";
}
前端傳輸數(shù)據(jù)如下:
$.post({
data: {
username: username, password: pwd
},
dataType: "text",
url: "/Home/LogOn",
success: function (result) {}});
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。