An example of Ajax refresh local page by jquery

Time:2021-1-13

Method 1

Partial refresh we talk about the most is Ajax, of course, you can not use ajax to refresh the page, we can use the append in jQuery to add things to the specified content, of course, the most practical is Ajax to load data.

For example, timed local refresh

Timed local refresh uses the setinterval method in jQuery. The setinterval method has two parameters. The first is to set the name of the function to be executed regularly, and the second is the time. As shown in the following code, set the AA method to be executed every 10 microseconds.


<script>
$(function(){
 setInterval(aa,10);
 function aa(){
   $("#aa").append("fdsadfsa");
 }
})
</script>

Example 2


<head>
<script src="jQuery/jquery-1.4.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
setInterval("startRequest()",1000);
});
function startRequest()
{
$("#date").text((new Date()).toString());
}
</script>
</head>

In example 3, let’s see how this refresh method is implemented.

JSP page Ajax

$("#waitWork").click(function(){
 Var url = request address;
 var data = {type:1};
 $.ajax({
  type : "get",
  Async: false, // synchronize request
  url : url,
  data : data,
  timeout:1000,
  success:function(dates){
  //alert(dates);
  $("#maincontent"). HTML (dates); // div to refresh
  },
  error: function() {
        //Alert ("failed, please try again later! "";
      }
 });
 });

html


<div>

Note: the background needs to use a separate JSP page for the information in div, otherwise you need to package the required page information to return

Method 2

From time to time, I need some mechanism to constantly refresh the page to provide a real-time dashboard of some kind. If I can only refresh a part of a specific page, it will be great, for example: the traffic lights on the dashboard show the system status.

It’s easy to refresh only part of the page by using the jQuery JavaScript library. Once we’re included in our page’s jQuery library, we only need one line

JavaScript gets its work:


<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>

So we just need to put this small JS code fragment into our page to refresh everything in the content ID tag. Let’s say, every 5 seconds:


setInterval(function() {
  $("#content").load(location.href+" #content>*","");
}, 5000);

This is it!! So it’s very easy to complete some real-time monitoring behavior, just that line of code. There is no stranger meta refresh tag or iframe as a solution in web applications.

Every 5 seconds, we will refresh the URL and all elements with the same content, and reside in the content with the element ID of content element: content.