Home  >  Article  >  Web Front-end  >  Ajax implements the function of long connection between server and browser

Ajax implements the function of long connection between server and browser

韦小宝
韦小宝Original
2018-01-10 09:54:542055browse

This article mainly introduces the relevant information about ajax’s function of realizing long connection between server and browser. It shares the ajax source code with everyone. Friends who are interested in ajax can refer to this article.

Yes Sometimes, the server needs to actively push data to the browser. Ajax is used to implement this function. Please see here for details:


<script type="text/javascript" src="CSS/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
  var uid = "{$uid}";
  var i = 0;
  var timer;
  $().ready(function(){
    //打开扫码登录模态框
    $(&#39;#login&#39;).click(function(){
      //如果用户已经登录,则返回
      if(uid){ 
        return ;
      }
      //打开模态框,通过remote选项从远程加载数据
      $(&#39;#loginModel&#39;).modal({
        remote: "{:U(&#39;user/login&#39;)}"
      });
    });
     
    //模态框隐藏之后清空数据
    $("#loginModel").on("hidden.bs.modal", function() {
      $(this).removeData("bs.modal");
    });
     
    //当模态框显示出来后,通过定时返回来向服务器请求数据,定时器是每三秒请求一次服务器
    $(&#39;#loginModel&#39;).on(&#39;shown.bs.modal&#39;, function (e) {
      timer = setInterval(ajax_request, 3000);
    });
  });
   
  //ajax 请求函数,
  function ajax_request(){
    i++;
    //如果已经请求20此没有请求成功,则强制结束,给出提示信息,因为每3s调用一次,供调用20次,大概就是一分钟的时间
    if(i > 20){
      $(&#39;.login_info1&#39;).html(&#39;<span style="color:red;">登录超时,如需登录请刷新页面~</span>&#39;);
      clearInterval(timer);
      return ;
    }
     
    $.ajax({
      type: "post",
      url: "{:U(&#39;User/login_qrcode&#39;)}",
      timeout : 3000,
      data: { "scene_id": $(&#39;#scene_id&#39;).val() },
      success: function (msg){        
        if(1 == msg.status){
          $(&#39;.login_info1&#39;).html(&#39;<span style="color:#0C9;">&#39;+msg.info+&#39;</span>&#39;);
          setTimeout(refresh, 3000);
          return ;
        }
      },
      error: function(){
      }
    });
  }
   
  //重载页面
  function refresh(){
    location.reload();
  }
</script>


The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

About the encapsulation example of ajax network request

Solution to the problem of Ajax rollback and refresh page

How to solve the problem when an AJAX request contains an array

The above is the detailed content of Ajax implements the function of long connection between server and browser. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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