Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 九九精品视频在线播放8,欧美视频亚洲,国产精品久久久久影院

          整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          JavaScript,原生、jQuery、Axios

          JavaScript,原生、jQuery、Axios,發送Ajax同步及異步請求代碼

          Web數據交互方式,Ajax:

          Ajax,Asynchronous Javascript And XML(異步JavaScript和XML),2005年被Jesse James Garrett提出的新術語,用來描述一種使用現有技術集合的新方法,包括:HTML或XHTML,CSS,JavaScript,DOM,XML,XSLT,以及最重要的XMLHttpRequest。 使用Ajax技術網頁應用能夠快速地將增量更新呈現在用戶界面上,而不需要重載(刷新)整個頁面,這使得程序能夠更快地回應用戶的操作。

          jQuery

          jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之后又一個優秀的JavaScript代碼庫(框架)于2006年1月由John Resig發布。封裝了JavaScript常用的功能代碼,提供一種簡便的JavaScript設計模式,優化HTML文檔操作、事件處理、動畫設計和Ajax交互。

          Axios

          一個基于promise的HTTP庫,可以用在瀏覽器和node.js中。

          跨域資源共享(CORS)

          CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。允許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。

          代碼案例

          原生的Ajax同步&異步代碼案例

          //Ajax Get 同步請求
          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 同步請求
          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 異步請求
          // rtnFun: 函數
          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 異步請求
          // rtnFun: 函數
          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為參數防止瀏覽器緩存 -->
              <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同步請求
                  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 同步請求
                  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 異步請求
                  console.log("請求前:" + 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("請求后:" + new Date().getTime());
          
                  // 4、Ajax Ajax Post 異步請求
                  console.log("請求前:" + 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("請求后:" + 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同步請求
                  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 同步請求
                  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 異步請求
                  $.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 異步請求
                  $.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異步請求
                  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);
                  });
                  // 另外一種寫法
                  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異步請求
                  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);
                  })
                  // 另外一種寫法
                  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同步請求
                  console.log("請求前:" + 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("執行1:" + new Date().getTime());
                      });
                      console.log("執行2:" + new Date().getTime());
                      return data;
                  }
                  const result=getData();
                  result.then(res=>{
                      console.log("執行3:" + new Date().getTime());
                      console.log("result31", res);
                      document.getElementById("result31").innerText=res;
                  })
                  console.log("請求后:" + new Date().getTime());
              </script>
          </body>
          </html>

          SpringBoot后臺代碼

          跨域的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);  // 值越小,Filter越靠前。
                  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()); //注冊
                  return new CorsFilter(source);
              }
          
          }
          

          Controller支持:

          .Net core中,當使用ajax提交json數據時,因為在.net core中是屬于強類型數據,所以在數據接受時可以使用[FromBody]標簽采用自定義注冊的方法,其代碼參考如下(以下代碼原文出處: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添加注冊

          services.AddMvc(options=>

          {

          options.ModelBinderProviders.Insert(0, new JObjectModelBinderProvider());//加入JobjectModelBinderProvider綁定

          });

          在后臺接受是如下

          [HttpPost]

          public stringLogin([FromBody]JObject data)

          {

          return "";

          }

          前端傳輸數據如下:

          $.post({

          data: {

          username: username, password: pwd

          },

          dataType: "text",

          url: "/Home/LogOn",

          success: function (result) {}});


          主站蜘蛛池模板: 欧美亚洲精品一区二区| 国产精品被窝福利一区 | 无码人妻av一区二区三区蜜臀| 无码一区二区三区视频| 亚洲AV福利天堂一区二区三| 国产精品一区二区久久| 国产伦精品一区二区三区精品 | 日本一区二区三区精品国产 | 在线精品亚洲一区二区小说| 亚洲av福利无码无一区二区 | 国产精品男男视频一区二区三区| 色一情一乱一伦一区二区三区| 中文字幕一区精品| 人妻天天爽夜夜爽一区二区| 国产福利酱国产一区二区| 精品一区二区三区色花堂| 3d动漫精品成人一区二区三| 国产精品一区二区四区| 久久国产三级无码一区二区| 久久国产精品无码一区二区三区| 成人精品一区二区激情| 国精无码欧精品亚洲一区| 成人免费视频一区| 国产成人精品一区二区秒拍| 久久精品无码一区二区三区不卡| 亚洲日韩国产一区二区三区| 亚洲一区在线视频观看| 日本一区二区三区在线视频观看免费| 亚洲av无码一区二区三区不卡| 无码视频一区二区三区| 国产成人精品一区二区秒拍| 国产女人乱人伦精品一区二区| 综合久久一区二区三区| 国模大胆一区二区三区| 亚洲AV综合色一区二区三区| 白丝爆浆18禁一区二区三区 | 精品国产一区二区三区免费看| 视频一区精品自拍| 波多野结衣一区二区免费视频| 人妻无码第一区二区三区| 国产精品一区二区久久精品无码|